gpt4 book ai didi

c - 编译时段错误的可能原因

转载 作者:行者123 更新时间:2023-11-30 19:02:49 25 4
gpt4 key购买 nike

问题:

我的程序正在运行,但未成功。它返回段错误。可能是哪里出了问题或者如何解决这个问题?

代码:

#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 循环语法是:

for ( init; condition; increment )

第二个 for 循环相同:for (i = 0; i < n, i++;) ,应该是 for (i = 0; i < n; i++)

<小时/>

您可以通过传递编译启用标志(例如Wall)来允许编译器警告您这一点。对于 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);
| ^~~~~~~~~~~~~~~

关于c - 编译时段错误的可能原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55207983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com