-1

Sorry, I'm a bit of a newbie to C and was wondering how you could create an array whose size is not known at compile time before the C99 standard was introduced.

user2246521
  • 83
  • 3
  • 11
  • Welcome on SO. Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. – epsilon Dec 27 '13 at 14:42
  • 1
    Please do not write new software in 1989 C. – Eric Postpischil Dec 27 '13 at 14:47

5 Answers5

1

Use malloc function from stdlib.h to create a dynamic array object.

ouah
  • 138,975
  • 15
  • 262
  • 325
1

the ordinary way would be to allocate the data on the heap

  #include <stdlib.h>
  void myfun(unsigned int n) {
    mytype_t*array = (mytype_t*)malloc(sizeof(mytype_t) * n);
    // ... do something with the array
    free(array);
  }

you could also allocate on the stack (so you don't need to free manually):

  #include <alloca.h>
  void myfun(unsigned int n) {
    mytype_t*array = (mytype_t*)alloca(sizeof(mytype_t) * n);
    // ... do something with the array
  }
umläute
  • 26,106
  • 8
  • 56
  • 114
1

It's very easy. For example, if you want to create a variable length 1D int array, do the following. First, declare a pointer to type int:

int *pInt;

Next, allocate memory for it. You should know how many elements you will need (NUM_INTS):

pInt = malloc(NUM_INTS * sizeof(*pInt));

Don't forget to free your dynamically allocated array to prevent memory leaks:

free(pInt);
Fiddling Bits
  • 8,422
  • 3
  • 27
  • 43
0

You can do this by dynamic memory allocation. Use malloc function.

haccks
  • 100,941
  • 24
  • 163
  • 252
0

malloc or calloc

YourType* ptr = malloc(sizeof(YourType)*NumberOfItemsYouNeed)
Digital_Reality
  • 4,220
  • 1
  • 24
  • 31