2

at design time I could have declare a variable like this:

char szDesignTimeArray[120][128];

The above declaration is 120 arrays of size 128. At run time I need to allocate the following:

char szRunTime[?][128];

I know the size of the arrays but I do not how many arrays I need to allocate. How can I declare this and allocate them when I know the number?

Thnaks all

2

3 Answers 3

6

I assume at run-time you know the Row_Size as well.

You can dynamically allocate a multidimensional array at run time, as follows:

#include <stdlib.h>

int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
    {
    fprintf(stderr, "out of memory\n");
    exit or return
    }
for(i = 0; i < nrows; i++)
    {
    array[i] = malloc(ncolumns * sizeof(int));
    if(array[i] == NULL)
        {
        fprintf(stderr, "out of memory\n");
        exit or return
        }
    }

Reference:

http://www.eskimo.com/~scs/cclass/int/sx9b.html

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

3 Comments

Remember that it's important to free the sub-arrays as well, and not only do free(array);.
Wouldn't calloc be used instead of malloc here?
And how would you memcpy this array to another location? How would you use bsearch, qsort etc? Oops. Don't use pointer-to-pointer notation, read up on array pointers instead.
3

With the length of the rows statically know, you could also allocate

char (*szRunTime)[128];
// obtain row count
szRunTime = malloc(rowCount * sizeof *szRunTime);

memory to a pointer to char[128]. That way, you get a contiguous block of memory, which may give better locality, and you need only free one pointer.

If the number of rows is not too large, using a variable length array,

rowCount = whatever;
char szRunTime[rowCount][128];

may however be the best option if C99 or later is supported.

1 Comment

This is the best solution by far. If you use the misguided (but common) pointer-to-pointer notation, you end up with the array declared in segments all over the heap. Such an array will not be compatible with various C library functions (mempcy, bsearch, qsort etc).
1

use this ,, where Variable is the how many array you want :

char **szRunTime = malloc(sizeof(char *)*Variable);
int i;
for(i=0 ; i<Variable ; i++)
    szRunTime[i] = malloc(sizeof(char)*128);

1 Comment

And how would you memcpy this array to another location? How would you use bsearch, qsort etc? Oops. Don't use pointer-to-pointer notation, read up on array pointers instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.