I am trying to add the sum of an array. I am using malloc function to allocate memory at first and then realloc function to reallocate memory. but the realloc function is not allocating any memory.
HERE IS MY CODE
#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);
}
}
}
It's because you changed the value of ptr
so that it no longer points to the original malloced memory. It happens here:
for(i=1;i<=s;i++){
scanf("%d",ptr);
sum+=*ptr;
ptr++; // ptr is changed
}
Instead of changing ptr
you should do:
for(i=0;i<s;i++){
scanf("%d",&ptr[i]); // or scanf("%d", ptr + i);
sum+=ptr[i];
}
BTW: When using scanf
always check that it scans the expected number of elements. Like:
if (scanf("%d",&ptr[i]) != 1)
{
// add error handling here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.