简体   繁体   中英

Dynamic Allocation 2D array

I need to implement 10 cols by a dynamic row lenght array which can hold a string. So far, i am trying to experiment by using an intiger instead of srings, for simplicity.

this is my code so far:

int** pArray = (int**)malloc(10*sizeof(int*));
for (i = 0; i < 10; i++ ) 
{
    pArray[i] = (int*)malloc(sizeof(int));
}

so now i know i created a 10x1 array. now i need to dynamically realoc each row according to the need that arises..

at this point i am stuck. Any assistance would be much apprieciated

A better approach than reallocating would be be to allocate the rows after you know how much memory is needed.

char ** pArray = (char **)malloc(10*sizeof(char*));
for(i=0;i<10;i++)
{
  pArray[i] = NULL;
}

And when you need to allocate row 'i' of size 'n', do

pArray[i] = (char*)malloc(n*sizeof(char));

我认为您需要realloc函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM