数组指针等价仅适用于函数arguments,因此虽然void fn(const char* argv[])
和void fn(const char** argv)
是等价的,但当涉及到您可能想要传递给函数的变量时,它并不成立。
考虑
void fn(const char** argv)
{
...
}
int main(int argc, const char* argv[])
{
fn(argv); // acceptable.
const char* meats[] = { "Chicken", "Cow", "Pizza" };
// "meats" is an array of const char* pointers, just like argv, so
fn(meats); // acceptable.
const char** meatPtr = meats;
fn(meatPtr); // because the previous call actually cast to this,.
// an array of character arrays.
const char vegetables[][10] = { "Avocado", "Pork", "Pepperoni" };
fn(vegetables); // does not compile.
return 0;
}
"vegetables" 不是指向指针的指针,它直接指向 3*10 连续字符序列中的第一个字符。替换上面的 fn(vegetables) 得到
int main(int argc, const char* argv[])
{
// an array of character arrays.
const char vegetables[][10] = { "Avocado", "Pork", "Pepperoni" };
printf("*vegetables = %c\n", *(const char*)vegetables);
return 0;
}
并且输出是“A”:蔬菜本身直接——没有间接地——指向字符,而不是中间指针。
蔬菜分配基本上是一个捷径:
const char* __vegetablesPtr = "Avocado\0\0\0Pork\0\0\0\0\0\0Pepperoni\0";
vegetables = __vegetablesPtr;
和
const char* roni = vegetables[2];
翻译成
const char* roni = (&vegetables[0]) + (sizeof(*vegetables[0]) * /*dimension=*/10 * /*index=*/2);