gpt4 book ai didi

c - 为什么我们不能像c中的指针一样增加数组呢?

转载 作者:行者123 更新时间:2023-11-30 18:52:46 25 4
gpt4 key购买 nike

#include <stdio.h>

int main(){
int arr[] = {1, 2, 3, 4};
int *p;
p = arr;
printf("%d\n", *p);
printf("%d\n", *arr);
p++;
printf("%d\n", *p);
}

此代码输出:

1
1
2

但是当我们添加如下两行时:

 #include <stdio.h>

int main(){
int arr[] = {1, 2, 3, 4};
int *p;
p = arr;
printf("%d\n", *p);
printf("%d\n", *arr);
p++;
printf("%d\n", *p);
arr++;
printf("%d\n", *arr);
}

此代码输出:

C:\Users\Hasnat\Desktop\test.c||In function 'main':|
C:\Users\Hasnat\Desktop\test.c|11|error: lvalue required as increment operand
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===

为什么我们不能以与增加包含该数组地址的指针相同的方式增加一个数组来获取下一个元素?

最佳答案

引用 C11,第 6.5.2.4 章,后缀递增和递减运算符

The operand of the postfix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.

可修改左值的定义在同一标准的第 6.3.2.1 章中给出,左值、数组和函数指示符

An lvalue is an expression (with an object type other than void) that potentially designates an object; [...] A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a constqualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a constqualified type.

因此,您不能在数组上使用++。简单。

关于c - 为什么我们不能像c中的指针一样增加数组呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34356291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com