Ç - '的char **'中的间接水平不同于'字符(*)[6]' [英] C - 'char **' differs in levels of indirection from 'char (*)[6]'
问题描述
可有人请向我解释什么地方错了以下内容,更重要的是,为什么?
Can someone please explain to me what's wrong with the following, and more importantly why?
int main( int argc, char *argv[] )
{
char array[] = "array";
char **test;
test = &array;
*test[0] = 'Z';
printf( "%s\n", array );
return 0;
}
修改
我上面的例子是基于这样被撞毁的函数:
My example above was based on a function like this that was crashing:
void apple( char **pp )
{
*pp = malloc( 123 );
*pp[0] = 'a'; // technically this is correct but in bad form
*pp[1] = 'b'; // incorrect but no crash
*pp[2] = '\0'; // incorrect and crash
}
由于虽然向我指出由沃恩卡托*页[0] ='A';
不会崩溃它是不好的形式。正确的方式是在括号
As pointed out to me by Vaughn Cato although *pp[0] = 'a';
does not crash it is in bad form. The correct form is the parenthesis
void apple( char **pp )
{
*pp = malloc( 123 );
(*pp)[0] = 'a'; // correct
(*pp)[1] = 'b'; // correct
(*pp)[2] = '\0'; // correct
}
另外,作为另一个海报MK指出,常见问题包括数组和指针的区别:
http://www.lysator.liu.se/c/c -faq / C-2.HTML
推荐答案
测试=安培;阵列
是错误的,因为测试的类型为的char **
和&放大器;阵列
是字符(*)[6]
距离字符不同类型的**
is wrong because test is of type char**
and &array
is a char(*)[6]
and is a different type from char**
数组是不是同一类型为的char *
尽管C将隐式数组类型和的char *之间的转换
在一些上下文中,但是这不是其中之一。基本上期望的char *
相同数组的类型(例如:的char [6]
)是错了,因此,服用一个数组的地址将导致字符的期望**
也是错误的。
An array isn't the same type as char*
although C will implicitly convert between an array type and a char*
in some contexts, but this isn't one of them. Basically the expectation that char*
is the same as the type of an array (e.g: char[6]
) is wrong and therefore the expectation that taking the address of an array will result in a char**
is also wrong.
这篇关于Ç - '的char **'中的间接水平不同于'字符(*)[6]'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!