多维数组作为平面数组问题
我正在查看某人编写的两行代码,第二行中有一个异常,但我不明白为什么。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
二维数组与指针数组不同。
您的第一条语句创建两个包含六个字符的数组,每个数组作为单个内存块。将该语句替换为:
然后您就可以完成第二个语句了。不要忘记
编辑 0:
呵呵,我应该知道:) 对于评论中的问题:
你不知道。不是这种形式。如果您正在为某些 C API 构建参数列表,例如
execve(2)
,你必须一路进行两阶段初始化: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:
and you'll be all set with your second statement. Don't forget to
Edit 0:
Huh, I should've known :) To your question in the comment:
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: