我无法使用malloc()和realloc()函数分配内存
我正在尝试添加数组的和。我首先使用malloc函数分配内存,然后使用realloc函数重新分配内存。但是realloc函数没有分配任何内存 这是我的密码我无法使用malloc()和realloc()函数分配内存,c,C,我正在尝试添加数组的和。我首先使用malloc函数分配内存,然后使用realloc函数重新分配内存。但是realloc函数没有分配任何内存 这是我的密码 #include<stdio.h> #include<conio.h> #include<stdlib.h> void main(){ int s,*ptr, *p,sum=0,i,*q; printf("\nEnter the
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
int s,*ptr, *p,sum=0,i,*q;
printf("\nEnter the size of array: ");
scanf("%d",&s);
ptr=(int *)malloc(s*sizeof(int));
p=ptr;
printf("\nMemory allocated: %u",ptr);
if(ptr==NULL){
printf("\nERROR! Insuffcient memory.");
exit(EXIT_FAILURE);
}
else{
printf("\nEnter the elements of array: ");
for(i=1;i<=s;i++){
scanf("%d",ptr);
sum+=*ptr;
ptr++;
}
printf("\nThe elements of arrays are: ");
for(i=1;i<=s;i++){
printf("%d\t",*p);
p++;
}
printf("\nThe Sum of array elements is: %d",sum);
printf("\nEnter the new Size of array: ");
scanf("%d",&s);
ptr=(int *)realloc(ptr , s * sizeof(int));
if(ptr==NULL){
printf("\nERROR!! Insufficient Memory!!");
exit(EXIT_FAILURE);
}
else{
printf("\nReallocated memory: %u",ptr);
q=ptr;
printf("\nEnter the elements of array: ");
for(i=1;i<=s;i++){
scanf("%d",ptr);
sum+=*ptr;
ptr++;
}
printf("\nThe elements of arrays are: ");
for(i=1;i<=s;i++){
printf("%d\t",*q);
q++;
}
printf("\nThe Sum of array elements is: %d",sum);
}
}
}
#包括
#包括
#包括
void main(){
整数s,*ptr,*p,和=0,i,*q;
printf(“\n输入数组的大小:”);
scanf(“%d”和“&s”);
ptr=(int*)malloc(s*sizeof(int));
p=ptr;
printf(“\n分配的内存:%u”,ptr);
如果(ptr==NULL){
printf(“\n错误!内存不足。”);
退出(退出失败);
}
否则{
printf(“\n输入数组的元素:”);
对于(i=1;i这是因为您更改了ptr
的值,使其不再指向原始malloced内存。发生在:
for(i=1;i<=s;i++){
scanf("%d",ptr);
sum+=*ptr;
ptr++; // ptr is changed
}
顺便说一句:当使用scanf
时,请始终检查它是否扫描了预期数量的元素。例如:
if (scanf("%d",&ptr[i]) != 1)
{
// add error handling here
}
可能您的scanf失败,随后realloc得到相同或随机的值。检查它只是添加新的size@xing是正确的,您应该保留起始地址并在realloc
中再次使用该地址,并且在realloc
之后将sum
重新初始化为零,或者将新的sum
添加到第一个地址数组onec中的数组是从零而不是从一开始索引的。因此循环是for(int i=0;i
@JonathanLeffler,我在他的for
循环中没有发现任何错误,他不是通过I
访问数组的索引,这只是一个计数器现在还是学习惯用的C循环更好,即使它们目前不是问题。而且因为OP没有索引,看起来ptr
和p
都增加了由于传递到realloc()
的指针不是由malloc()
返回的指针,也不是以前的realloc()
返回的指针,所以重新分配失败。我仍然误读了代码;这不会让我感到惊讶。但快速浏览一下就可以看出这一点。
if (scanf("%d",&ptr[i]) != 1)
{
// add error handling here
}