Possible Duplicate:
How do I work with dynamic multi-dimensional arrays in C?
pointer to array type, c
If my C89 ANSI (e.g. not C99) C code declares a variable AND allocates memory using:
char myArray[30000][3];
Is there a way I can de-couple the declaration from the memory allocation by using malloc()? For example (and pardon my newbie-ness):
char *myArray;
int i, arrayLength;
...
/* compute arrayLength */
...
myArray = malloc( sizeof(char) * arrayLength * 3);
for (i=0; ii<arrayLength; i++)
strncpy(myArray[i], "ab", 3);
...
free(myArray);
The goal is to create myArray looking like, for example:
myArray[0] = "ab"
myArray[1] = "ab"
myArray[2] = "ab"
...
myArray[arrayLength-1] = "ab"
Is that the right approach?
It looks like you want to make the first array size a variable run-time value (specified by
arrayLength), while keeping the second size as fixed compile-time value (3). In that specific situation it is easyThings will get more complicated if you decide to make the second array size a run-time value as well.
P.S.
strncpyis not supposed to serve as a “safe” version ofstrcpy(see https://stackoverflow.com/a/2115015/187690, https://stackoverflow.com/a/6987247/187690), so I usedstrcpyin my code. But you can stick withstrncpyif you so desire.