-1

I am wondering on how to create an integer array in C which you can expand it by one index every time you need to store additional values. I came across malloc and realloc and sizeof, but I really don't know how they work. Can someone here give a brief example on how to accomplish this in C.

Jason Ze
  • 73
  • 1
  • 2
  • 6
  • 1
    Please explain what it is you're ultimately trying to achieve. It may be that a linked-list or other data structure may be more suitable. Also, there are plenty of resources on the net to explain what malloc, et al, are and do. – Lee Taylor Aug 26 '14 at 00:40
  • 1
    See this question: http://stackoverflow.com/questions/3536153/c-dynamically-growing-array. It describes what you need. – Alex Kleiman Aug 26 '14 at 00:40

1 Answers1

0

If you want to resize your array you may do this:

int* arr = malloc(n*sizeof(int)); // n is your initial required array size
// now you need more
int* temp = realloc(arr,another_size*sizeof(int));
// check if reallocation is successful
if(temp!=NULL)
    arr = temp;

Here's How malloc, realloc works:
malloc man page
realloc man page

deeiip
  • 3,319
  • 2
  • 22
  • 33
  • Note: In the corner case when `another_size == 0`, returning `NULL` may be a sign of success. If `another_size == 0` is a possibility, better to use `if (temp != NULL || another_size == 0) arr = temp;` – chux - Reinstate Monica Aug 26 '14 at 03:12