gpt4 book ai didi

c - 为什么会崩溃? (缓冲区溢出)

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:19 25 4
gpt4 key购买 nike

#include <stdio.h>
#define N 100

int main()
{
int n,c,d,a[N],b[N];

printf("Insert elements numbers in the array\n");
scanf("%d ", n);

printf("Insert the elements in the array\n");

for (c = 0; c < n ; c++)
scanf("%d", a[c]);

for (c=n-1,d = 0;d < n; c--,d++)
b[d]= a[c];

for(c = 0; c <n; c++)
a[c] = b[n];

printf("The array inverted is\n");

for(c=0; c<n;c++)
printf("%d\n",a[c]);

return 0;
}

为什么会崩溃?我已经尝试过,即使值 (N < 100) 但仍然崩溃,我不知道如何修复它?有人能帮助我吗 ?谢谢!

最佳答案

这个:

scanf("%d ", n);

调用未定义的行为。 scanf() 需要一个指向数字存储位置的指针,它应该是:

scanf("%d ", &n);

其余的 scanf() 调用也是如此。此外,在依赖包含有效值的变量之前,您应该检查返回值以了解它是否成功读取数据。

关于c - 为什么会崩溃? (缓冲区溢出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21682520/

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