I'm looking at two lines of code that somebody wrote and there is an exception in the 2开发者_StackOverflow社区nd one, however I don't understand why.
char** array = (char**) new char [2] [6];
std_strlprintf(array[0],6,"[%d]", num);
std_strlprintf is a Brew function that writes formatted output to a string. (num is an integral value which is 0)
Why is there an exception with this code, what's wrong with accessing the first elelment of the array as buff[0]?
EDIT: sorry there was a typo in my initial posting. Its corrected now. THis is the code that has the exception.
Two-dimensional array is not the same as array of pointers.
Your first statement creates two arrays of six chars each as a single memory block. Replace that statement with:
char (*array)[6] = new char [2][6];
and you'll be all set with your second statement. Don't forget to
delete [] array;
Edit 0:
Huh, I should've known :) To your question in the comment:
How should I subsequently pass array to a function that takes a
char**
as a parameter?
You don't. Not in this form. If you are building a list of parameters to some C API like execve(2)
, you have to go all the way with two-stage initialization:
// prototype of the function to call
void my_fancy_func( int argc, char* const argv[] );
char** my_argv = new char*[my_argc];
for ( i = 0; i < my_argc; i++ ) {
my_argv[i] = new char[arg_buffer_size];
snprintf( my_argv[i], arg_buffer_size, "%d", i );
}
my_fancy_func( my_argc, my_argv );
精彩评论