gpt4 book ai didi

c - 为什么这段 C 代码会崩溃? (有指针)

转载 作者:行者123 更新时间:2023-11-30 18:20:39 25 4
gpt4 key购买 nike

这是我的 C 类的练习,其中用户输入两个整数 ab,我必须创建一个函数,返回一个包含之间所有整数的数组ab:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int* arrayfromatob(int a,int b,int *p)
{
int i;
for(i=0;i<=b-a+1;i++)
p[i]=a+i;
return p;
}

main()
{
int a,b,*p,i,temp;
puts("Give two integers:");
scanf("%d %d",&a,&b);
if(b<a)
{
temp=a;
a=b;
b=temp;
}
p=(int*)calloc(b-a+1,sizeof(int));
if(p==NULL)
{
puts("Could not allocate memory");
exit(1);
}
p=arrayfromatob(a,b,p);
for(i=0;i<b-a+1;i++)
printf("Number %d: %d\n",i+1,p[i]);
free(p);
system("pause");
}

为什么这段代码会崩溃? (我认为这与 free(p); 有关,但我不确定......)

最佳答案

    for(i=0;i<=b-a+1;i++)
p[i]=a+i;

您正在访问 b - a + 2 元素。但是您在以下位置分配了 b - a + 1 元素:

p=(int*)calloc(b-a+1,sizeof(int));

关于c - 为什么这段 C 代码会崩溃? (有指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15585743/

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