gpt4 book ai didi

c - c中为数组分配内存时出现段错误

转载 作者:行者123 更新时间:2023-11-30 14:50:53 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int n,i=3;
printf("Enter number of elements you want in array:");
scanf("%d",&n);
ptr=(int *)malloc(n*sizeof(n));
if(ptr=NULL)
{
printf("Memory Not Allocated!!");
return 0;
}
else
{
printf("Memory allocation succesful\n");
int *arr;
printf("write elements here\n");
for(arr=ptr;arr<ptr+n;arr++)
{
scanf("%d",arr);
printf("Hello world");
printf("\n");
}
for(arr=ptr;arr<ptr+n;arr++)
{
printf("%d",*arr);
}
free(ptr);
return 0;
}
}

每当我运行此代码时,在接受输入时它都会停止工作。所以我后来尝试在在线编译器中检查,它给出了段错误。

请帮帮我!

最佳答案

这一行:

if(ptr=NULL)

应该是:

if(ptr==NULL)

否则,ptr 会被赋予 NULL 值,并且 ptr=NULL 的计算结果为 false。因此,else 子句在将ptr 分配给NULL 后立即运行。

另一件事,为了提高 for 循环的可读性,这更具可读性:

   for(int i = 0; i < n; i++)
{
scanf("%d",&ptr[i]);

for 语句是标准的说法,循环 n 次。使用 &ptr[i] (或 ptr+i)使得引用哪个地址变得更加明显。

关于c - c中为数组分配内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48700093/

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