PDA

View Full Version : Dynamic memory allocation of arrayed char



Starnut coder
09-10-2002, 03:46 AM
I'm having problems allocating memory for an array of strings. Here's my code:
(char **val1 = NULL and char **val2 = NULL exist).
There seems to be a problem as to where the pointers are pointing in memory since val1 sometimes returns the content of val2. Thanks for any help in advanced.



char **tmpval1;
if((tmpval1 = (char**)realloc(val1, size*sizeof(char))) == NULL)
{
return ERROR_MEM;
}
val1 = tmpval1;

char **tmpval2;
if((tmpval2 = (char**)realloc(val2, size*sizeof(char))) == NULL)
{
return ERROR_MEM;
}
val2 = tmpval2;

Robbo
09-10-2002, 07:40 AM
Achtung!

It appears to me that you are allocating an array of chars and storing a pointer to the allocated data as a pointer to a pointer to chars.

If you want to allocate a single string, you write char *tmpval1 rather than char**tmpval1.

char **tmpval1;
if((tmpval1 = (char**)realloc(val1, size*sizeof(char))) == NULL)
{
return ERROR_MEM;
}
val1 = tmpval1;
char **tmpval2;
if((tmpval2 = (char**)realloc(val2, size*sizeof(char))) == NULL)
{
return ERROR_MEM;
}
val2 = tmpval2;

l33t
09-10-2002, 07:12 PM
j00 t4k3 C pr0grmng 101 y3t ?