You are here:

C/dinamic Hashtable, problems with malloc and realloc

Advertisement


Question

-------------------------

Followup To

Question -
hi!

I have this declaration:
----------------------------------
static spam_item *HashTab[101];
----------------------------------

(spam_item is a struct that i made)

what i want do do is increase the size of HashTab, for example to 202 (the double), without losing the information i have on the HashTab.

Example: HashTab has 101  positions, each one pointing to a struct. The positions HashTab[0], HashTab[20] and HashTab[99] point to structs. All the other positions point to null.
  What i want is to increase the size of HashTab so that HashTab has 202 positions and the information on positions 0,20 and 99 isn't lost.


Thanks for all

Vando


Answer -
Use realloc() with new size.
It will retain the old data and changes the size to new value.

If your data is too sensitive and you want to make sure that nothing is lost, then you can create a temporary buffer, copy the data to temp buffer, use realloc to expand the size and then copy back from temp buffer.

------------------------------

Thanks Narendra but how really need to spell it out for me. I had the statement:

HashTab = (spam_item *) realloc (HashTab, M*sizeof(spam_item));

(M=202)

that statement gives me the following error:

error: incompatible types in assignment

how should my statement be?


Thanks

Vando

Answer
HashTab is an ARRAY of pointers.
And the size of this ARRAY is 101.
This is fixed and you can never change!

I thought that you have malloc'ed some size and want to increase and that's why I suggested realloc.

So, whatever error you are getting is correct only:-)

The only solution, you can have is, to change the declaration of:   
static spam_item *HashTab[101];
to:
static spam_item **HashTab = (spam_item *) malloc(101 * sizeof(spam_item));

If you follow this way, then you can always use realloc() to change the size of HashTab.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.