1

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?

Community
  • 1
  • 1
ggkmath
  • 4,188
  • 23
  • 72
  • 129
  • Why do you want to "decouple the memory allocation," as you put it? Note that no matter what you do, you will still be allocating memory, just where and how you do so may change. – Maz Nov 21 '12 at 02:49
  • Because 30000 is a "guess" what the worst case number of rows might be. It'd be much better to use the actual number of rows, which isn't known until the program runs. – ggkmath Nov 21 '12 at 02:50

1 Answers1

3

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 easy

char (*myArray)[3];
int arrayLength;
...
/* compute arrayLength */
...
myArray = malloc(arrayLength * sizeof *myArray);
for (i = 0; i < arrayLength; ++i) 
  strcpy(myArray[i], "ab");
...
free(myArray);

Things will get more complicated if you decide to make the second array size a run-time value as well.

P.S. strncpy is not supposed to serve as a "safe" version of strcpy (see https://stackoverflow.com/a/2115015/187690, https://stackoverflow.com/a/6987247/187690), so I used strcpy in my code. But you can stick with strncpy if you so desire.

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Yes, that's my goal, but my gcc version isn't C99 compatible so variable-length arrays are out. Would the above be C89 compatible? The number of columns (e.g. second array size) is always static here. – ggkmath Nov 21 '12 at 02:51
  • 1
    @ggkmath: Yes, the above is pure C89/90. No reliance on C99 VLAs. – AnT stands with Russia Nov 21 '12 at 02:52