/ array

Changing size of array in C programming language

It’s been a long time since I coded in C. I needed to change the size of an array within the program. At first I just simply tried;

int ab=10; 
int array[ab];

And surprisingly it didn’t work. (I mean it works in C++ and C#)
Anyway I was thinking of ways on how to do this thought of using malloc() however I really didn’t know how hence I did some Google’ing around. And found this neat piece of code.

int *resize_array(int *a, size_t new_size)
{
  int *save;

  save = realloc(a, new_size);
  if (save == NULL) {
    fprintf(stderr, "Memory exhaustedn");
    exit(EXIT_FAILURE);
  }
  return save;
}

int *user_old_array; // the array
int new_array_size=10;
user_old_array = malloc(initial_array_size * sizeof *user_old_array); //resized array

Quite neat isn’t it. I thought I should probably write this somewhere so I won’t forget. Hence the post.

Enjoy!

John Roach

John Roach

I am John Roach, a devops architect. Find more information here: https://johnroach.io/about/

Read More
Changing size of array in C programming language
Share this