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.
Asked
Active
Viewed 2,020 times
-1
-
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
-
1Please do not write new software in 1989 C. – Eric Postpischil Dec 27 '13 at 14:47
5 Answers
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
-
***Big, bold, italic "thanks"*** for suggesting `sizeof(*pointer)` instead of `sizeof(type)`. – Dec 27 '13 at 14:30
-
-
-
-
@haccks (If we accept that, it means that almost everyone did something fundamentally wrong then...) – Dec 27 '13 at 14:31
-
-
-
1
-
-
1
-
-
@FiddlingBits What is the reason to use `sizeof(*ptr)` instead of `sizeof(type)`? Could you provide a link please? – Utku Apr 23 '16 at 07:51
-
1@FiddlingBits Oh, is that because if you change the type of a variable, you don't need to change your `sizeof` code if you had written it as `sizeof(*ptr)` right? Is this the reason? – Utku Apr 23 '16 at 08:00
-
1@Utku Correct! You may introduce a subtle bug if you change the type of the variable, but not what you're using `sizeof` on. – Fiddling Bits Apr 23 '16 at 22:54
0
malloc or calloc
YourType* ptr = malloc(sizeof(YourType)*NumberOfItemsYouNeed)

Digital_Reality
- 4,488
- 1
- 29
- 31
-
2[Do ***NOT*** cast the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)! – Dec 27 '13 at 14:25
-
-
2