指针和数组语法之间的区别

时间:2014-11-11 15:38:22

标签: c arrays pointers posix

我对C非常陌生,我正在弄清楚语法。但我对以下差异感到困惑。如果有人可以解释他们的差异以及这对我如何操纵他们的意义。感谢

 char  *word 
 char **word 
 char  array[] 
 char *array[]

2 个答案:

答案 0 :(得分:1)

char  *word      //pointer to char
char **word      //pointer to a pointer to a char
char  array[]    //array of char of undefined size
char *array[]    //array of pointers to char of undefined size

现在你所要做的就是阅读一本关于“搞清楚语法”的指南。

答案 1 :(得分:1)

C声明基于表达式的类型,而不是对象。

例如,假设您有一个指向名为p的整数的指针,并且您想要访问p指向的值。您可以像这样使用解除引用运算符*

x = *p;

表达式 *p产生类型int的值,因此声明写为

int *p; // which is parsed as int (*p); the * is bound to the identifier p,
        // not the type specifier

对于稍微复杂的示例,您有一个指向char的指针数组,并且您想要访问指向的字符。您将索引到数组并取消引用结果:

c = *a[i]; // which is parsed as `*(a[i])`

同样,表达式 *a[i]的类型为char,因此a的声明已写入

char *a[N];

所以,通过具体的例子:

char  *word;   // word is a pointer to char
char **word;   // word is a pointer to a pointer to char
char array[];  // array is an array of char 
char *array[]; // array is an array of pointers to char

请注意,数组声明必须包含大小或具有初始值设定项;你的数组声明 不正确。

数组下标运算符[]和函数调用()的优先级高于一元*,所以:

T *a[N];     // a is an N-element array of pointer to T
T (*a)[N];   // a is a pointer to an N-element array of T
T *f();      // f is a function returning a pointer to T
T (*f)();    // f is a pointer to a function returning T