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

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Sunscreen
  • 3,452
  • 8
  • 34
  • 40

3 Answers3

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

Sandeep Singh
  • 4,941
  • 8
  • 36
  • 56
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.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • 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). – Lundin Sep 07 '12 at 12:48
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);
Rami Jarrar
  • 4,523
  • 7
  • 36
  • 52
  • 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. – Lundin Sep 07 '12 at 12:53