-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
  • 12
  • 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
  • 142,963
  • 15
  • 272
  • 331
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
  • 28,885
  • 9
  • 68
  • 122
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,712
  • 3
  • 28
  • 46
0

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

haccks
  • 104,019
  • 25
  • 176
  • 264
0

malloc or calloc

YourType* ptr = malloc(sizeof(YourType)*NumberOfItemsYouNeed)
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31