int main()
{
int t, i;
int *nums;
scanf("%d", &t);
nums = malloc(t * sizeof(int));
for(i = 0; i < t; i++)
{
scanf("%d", &nums[i]);
}
printf("hey");
}
由于某些原因,它挂起了,等待更多的输入!有什么想法吗?
这段代码是正确的,除了你没有释放内存(对于这个简单的代码来说不是很大问题),以及你没有检查 scanf
的错误,这可能是导致问题的原因。
下面是一个更好的实现,包括错误检查和正确的内存处理:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t, i, ret;
int *nums;
ret = scanf("%d", &t);
if(ret != 1)
{
/* something wrong */
}
nums = malloc(t * sizeof(int));
if(nums==NULL)
{
/* memory error */
}
for(i = 0; i < t; i++)
{
ret = scanf("%d", &nums[i]);
if(ret != 1)
{
/* something wrong */
}
}
free(nums);
printf("hey");
return 0;
}
这只是一个猜测...
但我猜想你运行了它并输入了:
4
1234
4
1234
29
4
5
你应该得到:
hey
scanf("%s", &t);
或者你已经收到了“嗨”的消息,只是没有看到它。
[ov@MARVIN sotest]$ ./a.out
5 5 4 3 23 1
hey[ov@MARVIN sotest]$
printf("hey");
更改为
printf("hey\n");
printf("hey");
fflush(stdout);
scanf()
的结果总是一个好主意。// scanf("%d", &t)
if (1 != scanf("%d", &t)) Handle_BadInput_or_EOF();
printf(“hey”);
更改为printf(“hey\n”);
。 - chux - Reinstate Monicaprintf
之后使用fflush(stdout);
- Spikatrix