0

I am a beginner coder in C and I recently learned the concept of dynamic arrays using calloc/malloc in C but I seem to have ran in a program.

This program right here asks for 10 elements from the user and then asks if you want to add more into it? depending on the value entered, realloc function is supposed to reallocate more memory for further elements, but the code just terminates when it reaches the realloc statement. Please help.

#include<stdio.h>
#include<stdlib.h>

int* arr;
size_t arrSize = 10;

int main(){
int modSize;
printf("The Program is making a dynamic array\n");
arr = calloc(arrSize,sizeof(int));
if(arr == NULL){
    printf("error from calloc\n");
}
printf("Enter Values for the Array: \n");
for(int i=0; i<arrSize; ++i){
    scanf("%d",&arr[i]);
}

printf("Would you like to add more values? If yes type the amount : ");
scanf("%d",&modSize);

arrSize += modSize;
arr = realloc(arrSize,arrSize*sizeof(int));
if(arr == NULL){
    printf("error from realloc\n");
}

for(int i = 10; i<arrSize; ++i){
    scanf("%d",&arr[i]);
}

for(int i = 0; i<arrSize; ++i){
    printf("%d\t",arr[i]);
}

free(arr);
return 0;
}

output

roverrr
  • 59
  • 3
  • You're unlikely to run into it in a simple example like this, but you might want to take a look at [Proper usage of realloc()](https://stackoverflow.com/questions/21006707/proper-usage-of-realloc) for how to handle a possible out of memory situation. – Retired Ninja Jul 14 '22 at 09:19
  • Thank you for notifying me, It's fixed and it is working. It was my first time using the dynamic allocation functions so I whiffed. Again, Thank you. – roverrr Jul 14 '22 at 09:25

1 Answers1

2

Your compiler should have told you that:

<source>:23:15: error: invalid conversion from 'size_t' {aka 'long unsigned int'} to 'void*' [-fpermissive]
   23 | arr = realloc(arrSize,arrSize*sizeof(int));
      |               ^~~~~~~
      |               |
      |               size_t {aka long unsigned int}

The first argument to realloc is the memory to reallocate, not a size:

void *realloc( void *ptr, size_t new_size );

Parameters

  • ptr - pointer to the memory area to be reallocated
  • new_size - new size of the array in bytes

In other words,

arr = realloc(arr, arrSize*sizeof(int));

is more correct, but please do turn on all errors and warnings in your compiler settings and heed them.

AKX
  • 152,115
  • 15
  • 115
  • 172