How can allocate multi dimensional array at run time?

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


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);

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


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.

Need Your Help

Drupal login via Rest server

jquery json drupal rest login

I'm developing a website who uses an external Drupal for the articles and pages.

Make iPhone app available for iPad download

ipad store

I have a iphone app that is in the app store and can be downloaded.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.