[英]Possible Causes of Segmentation Error during Compilation
我的程序正在运行,但没有成功。 返回分段错误。 可能出什么问题或如何解决此问题?
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int *arr, i, j, n;
printf ("Input the Size");
scanf ("%d", n);
arr=(int*)malloc(n*sizeof(int));
for (i = 0; i < n, i++;)
{
*(arr + i) = i;
}
for (i = 0; i < n, i++;)
{
printf ("%d\n", *(arr + i));
}
return 0;
}
更改此:
scanf ("%d", n);
对此:
scanf ("%d", &n);
因为scanf( const char * format, ...)
需要一个指针作为其参数。
此外更改此:
for (i = 0; i < n, i++;)
对此:
for (i = 0; i < n; i++)
因为通常的for循环语法是:
对于(init; condition;递增)
与第二个for循环相同: for (i = 0; i < n, i++;)
,应该for (i = 0; i < n; i++)
您可以通过传递启用编译的标志(例如Wall
for GCC)来允许您的编译器对此发出警告,例如Wall
for GCC(这样的编译: gcc prog.c -Wall
)。 然后,您将收到以下警告:
prog.c: In function 'main':
prog.c:7:12: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
7 | scanf ("%d", n);
| ~^ ~
| | |
| | int
| int *
prog.c:9:20: warning: left-hand operand of comma expression has no effect [-Wunused-value]
9 | for (i = 0; i < n, i++;)
| ^
prog.c:13:20: warning: left-hand operand of comma expression has no effect [-Wunused-value]
13 | for (i = 0; i < n, i++;)
| ^
prog.c:5:16: warning: unused variable 'j' [-Wunused-variable]
5 | int *arr, i, j, n;
| ^
prog.c:7:3: warning: 'n' is used uninitialized in this function [-Wuninitialized]
7 | scanf ("%d", n);
| ^~~~~~~~~~~~~~~
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.