指针数组中的递增运算符有什么问题?

时间:2022-01-09 15:40:13

I just found a little confusion while using increment operator in pointer array.

我在指针数组中使用递增运算符时发现了一点混乱。

Code 1:

int main(void) {
     char *array[] = {"howdy", "mani"};
     printf("%s", *(++array));
     return 0;
}

While compiling, gcc throws a well known error "lvalue required as increment operand".

在编译时,gcc抛出一个众所周知的错误“左值作为递增操作数”。

But, when I compile the below code it shows no error!!! Why?

但是,当我编译下面的代码时,它显示没有错误!为什么?

Code2:

int main(int argc, char *argv[]) {
     printf("%s",*(++argv));
     return 0;
}

In both cases, I have been incrementing an array of pointer. So, it should be done by this way.

在这两种情况下,我一直在增加一个指针数组。所以,应该通过这种方式来完成。

char *array[] = {"howdy","mani"};
char **pointer = array;
printf("%s",*(++pointer));

But, why code2 shows no error?

但是,为什么code2没有显示错误?

1 个解决方案

#1


5  

Arrays cannot be incremented.

数组不能递增。

In your first code sample you try to increment an array. In the second code sample you try to increment a pointer.

在第一个代码示例中,您尝试增加一个数组。在第二个代码示例中,您尝试增加指针。

What's tripping you up is that when an array declarator appears in a function parameter list, it actually gets adjusted to be a pointer declarator. (This is different to array-pointer decay). In the second snippet, char *argv[] actually means char **argv.

让你振作的是,当数组声明符出现在函数参数列表中时,它实际上被调整为指针声明符。 (这与数组指针衰减不同)。在第二个片段中,char * argv []实际上意味着char ** argv。

See this thread for a similar discussion.

有关类似的讨论,请参阅此主题。

#1


5  

Arrays cannot be incremented.

数组不能递增。

In your first code sample you try to increment an array. In the second code sample you try to increment a pointer.

在第一个代码示例中,您尝试增加一个数组。在第二个代码示例中,您尝试增加指针。

What's tripping you up is that when an array declarator appears in a function parameter list, it actually gets adjusted to be a pointer declarator. (This is different to array-pointer decay). In the second snippet, char *argv[] actually means char **argv.

让你振作的是,当数组声明符出现在函数参数列表中时,它实际上被调整为指针声明符。 (这与数组指针衰减不同)。在第二个片段中,char * argv []实际上意味着char ** argv。

See this thread for a similar discussion.

有关类似的讨论,请参阅此主题。