传递一个字符指针数组功能 [英] Passing a char pointer array to a function
问题描述
我已经写了下面的示例code来证明我的问题
I have written following sample code to demonstrate my problem
#include <iostream>
#include <string.h>
using namespace std;
void f (char*** a)
{
*a = new (char*[2]);
*a[0] = new char[10];
*a[1] = new char[10];
strcpy(*a[0], "abcd");
strcpy(*a[1],"efgh");
}
int main ()
{
char** b = NULL;
f(&b);
cout<<b[0]<<"\n";
cout<<b[1]<<"\n";
return 1;
}
在此code,我发现的 =一个新的(字符的[2]);不分配的内存*一个[1]。
In this code i found that a = new (char[2]); not allocating memory of *a[1].
在gdb中我得到以下赛格故障。
In gdb i am getting following seg fault.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400926 in f (a=0x7fffffffdfe8) at array1.cpp:10
10 *a[1] = new char[10];
(gdb) p *a[1]
Cannot access memory at address 0x0
这是真的困惑我。有人可以解释我要去的地方错了。
This is really confusing me. Can someone explain where i am going wrong.
我知道我可以通过像无效˚F参数(字符**放大器;一),并通过调用函数f(b)和工作原理。但我想知道要发生的事情,如果我使用CHAR ***一个。它也应该工作。很抱歉,如果这是一个愚蠢的问题。结果
对上述问题的任何教程或引用将AP preciated。结果
提前致谢。
I know i can pass argument like void f (char**& a) and by calling function f(b) and this works . But i want to know want happening if i use char*** a. It should also work. Sorry if this is an stupid question.
Any tutorial or reference on above problem will be appreciated.
Thanks in advance.
推荐答案
这是因为运算符precedence ,数组索引运算符 []
有更高的precedence比引用操作 *
。
It's because of the operator precedence, where the array-indexing operator []
have higher precedence than the dereference operator *
.
所以前pression * A [0]
是真的,从编译器的角度来看,同为 *(一[0])
,这是不是你想要的。
So the expression *a[0]
is really, from the compilers point of view, the same as *(a[0])
, which is not what you want.
您必须明确添加括号改变precedence:
You have to explicitly add parentheses to change the precedence:
(*a)[0] = ...
这篇关于传递一个字符指针数组功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!