Background:
I created an array using calloc(), and everything was working great. Then I used realloc() to make the array larger. It seems to just create a new pointer with nothing in it and calling a runtime error when I try to access elements in the array.
My Code:
#include <stdio.h>
int main() {
int *arr;
for (int i = 0; i < 5; i++){
if (i == 0) {
if ((arr = (int *) calloc(1, sizeof(int))) == NULL) {
printf("NO MORE SPACE TERMINATING PROGRAM");
return NULL;
}
} else {
int *tmp;
if ((tmp = (int *)realloc(arr, 4*sizeof(int)) == NULL)){
printf("NO MORE SPACE TERMINATING PROGRAM");
}
arr = tmp;
}
arr[i] = i;
}
}
It throws a runtime error on the line arr[i]=i;
when i = 1;
When I add a breakpoint 1 line above arr = temp;
it shows that temp is completely blank.
Why is this happening?
--------Update----------------
Thanks for all of the help. Here is the working updated code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int *arr = NULL;
for (int i = 0; i < 5; i++){
int *tmp;
if ((tmp = realloc(arr, (i+1) * sizeof(int))) == NULL){
printf("NO MORE SPACE TERMINATING PROGRAM");
}
arr = tmp;
arr[i] = i;
}
for (int i = 0; i < 5; i++) {
printf("%i",arr[i]);
}
}
The output is: 01234
Thanks everyone for your help.