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?

2
  • 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. Commented Nov 21, 2012 at 2: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. Commented Nov 21, 2012 at 2:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: Yes, the above is pure C89/90. No reliance on C99 VLAs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.