多维数组作为平面数组问题

发布于 2024-10-25 07:20:00 字数 315 浏览 0 评论 0原文

我正在查看某人编写的两行代码,第二行中有一个异常,但我不明白为什么。

char** array = (char**) new char [2] [6];

std_strlprintf(array[0],6,"[%d]", num);

std_strlprintf 是一个 Brew 函数,它将格式化输出写入字符串。 (num是一个整数值,为0)

为什么这段代码会出现异常,将数组的第一个元素作为buff[0]访问有什么问题?


编辑:抱歉,我最初的帖子中有一个拼写错误。现在已更正。 这是有异常的代码。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自控 2024-11-01 07:20:00

二维数组与指针数组不同。

您的第一条语句创建两个包含六个字符的数组,每个数组作为单个内存块。将该语句替换为:

char (*array)[6] = new char [2][6];

然后您就可以完成第二个语句了。不要忘记

delete [] array;

编辑 0:

呵呵,我应该知道:) 对于评论中的问题:

随后我应该如何传递数组
到一个以 char** 作为参数的函数
参数?

你不知道。不是这种形式。如果您正在为某些 C API 构建参数列表,例如 execve(2),你必须一路进行两阶段初始化:

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

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 );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文