Dec 26, 2008 at 1:55am UTC
What would be the better way to set up an cstring array; Method 1 or Method 2?
Method 1:
1 2 3 4 5 6 7
char **stringarray;
stringarray = new char *[stringcount];
for (int i=0; i < stringcount; i++){
stringarray[i] = new char [STRING_MAX_LENGTH];
memset(stringarray[i], 0, STRING_MAX_LENGTH);
}
or simply Method 2:
char stringarray[stringcount][STRING_MAX_LENGTH];
Currently I'm using Method 1, 'cause I know that I can set the memory free like this:
1 2 3 4
for (int i = 0; i < tokencount; i++){
delete [] stringarray[i];
}
delete [] stringarray;
Can I free memory like this for Method 2 as well or do I have to fear to fumble into memory not allocated?
I ask because doing Method 2 and deleting with the presented loop I got a compiler warning
warning: deleting array char stringarray[((unsigned int)((int)tokencount))][1024]
. So far my program did work, but I expirienced that I could compile and run programs that should fail, just by pure luck.
Last edited on Dec 26, 2008 at 1:56am UTC
Dec 26, 2008 at 3:37am UTC
Method 1 will always work if stringcount is a variable regardless of compiler. GCC allows creating arrays of variable size in the stack, but this is not standard, AFAIK.
As far as I can tell, your deletion snippet works if tokencount==stringcount.
Last edited on Dec 26, 2008 at 3:37am UTC