Multidimensional array as a flat array problem

爱⌒轻易说出口 提交于 2019-12-24 06:16:10

问题


I'm looking at two lines of code that somebody wrote and there is an exception in the 2nd 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.


回答1:


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 );


来源:https://stackoverflow.com/questions/5397976/multidimensional-array-as-a-flat-array-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!