I am writing a code which uses realloc(). The following is a simplified version of the problem. Though the code looks obvious yet it doesn't seem to work.
// Program for implementing variable length integer array.
#include<stdio.h>
#include<stdlib.h>
void add(int* ptr,int len,int ele){
ptr = (int*)realloc(ptr,len);
*(ptr+len-1) = ele;
}
void main(){
int max_len = 10;
int* arr = (int*)malloc(sizeof(int));
for(int i=0;i<max_len;i++)
add(arr,i+1,i+1);
printf("The elements are...\n");
for(int i=0;i<max_len;i++)
printf("%d\n",*(arr+i));
}
The program runs for max_len=8 or low but not beyond it. Why is this happening? Thanks in advance.
A few things:
First, you should pass your array by reference with
&. You pass your pointer by value which has no effect.Second, you forgot to make your realloc with
sizeof(int), equivalent to 4.Third, you have to assign your value the following way:
*(*(ptr) + len - 1) = ele;See the corrected code below:
output: