0

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

  • If it were me I wouldn't allocate the rows until I knew how much. Just set the pointer to NULL and when you go to access it and it is NULL then allocate the space. – Jerry Jeremiah Oct 25 '13 at 09:57
  • 1
    [Also do not cast the result of malloc.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – pzaenger Oct 25 '13 at 09:57
  • For matrixes allocate one vector and calculate complex index (e.g.: `col*rows+row`) is more effective. I would never do it on your way. (What is the price of allocating? What is the price of change memory context (reload data to cache)? Etc.) – Naszta Oct 25 '13 at 10:01
  • The problem is that i do not know how much data will the coloums have. I disire that it would expand if the need arises – eromlig Oct 25 '13 at 13:47

2 Answers2

1

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));
jester
  • 3,491
  • 19
  • 30
  • Practically i am implementing a hashing algoritith and if a colision happens i will store in the same row but a different coloumn, thats my idea. i dont know if its the right approach – eromlig Oct 25 '13 at 10:43
0

I think you want the realloc function.

doron
  • 27,972
  • 12
  • 65
  • 103