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

asked Oct 25, 2013 at 9:53
4
  • 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. Commented Oct 25, 2013 at 9:57
  • 1
    Also do not cast the result of malloc. Commented Oct 25, 2013 at 9: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.) Commented Oct 25, 2013 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 Commented Oct 25, 2013 at 13:47

2 Answers 2

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));
answered Oct 25, 2013 at 10:07
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

I think you want the realloc function.

answered Oct 25, 2013 at 9:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.