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 exhausted\n");
    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!

Fork me on GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">