这是我的 C 类的一个练习,其中用户输入两个整数a
,b
并且我必须创建一个函数,该函数返回一个数组,该数组包含 和 之间的所有a
整数b
:
#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); ,但我不确定......)