gpt4 book ai didi

c - 在 C 中打印数组元素的地址时出错

转载 作者:行者123 更新时间:2023-11-30 20:24:53 24 4
gpt4 key购买 nike

我收到一条错误消息:

cannot increment value of type int[2]

这是因为int的大小还是什么?

int arr[2]={10,20};
printf("%p \t %p \t",arr,++arr);

最佳答案

无法修改其值的唯一原因是您使用n定义了静态数组 > 大小,然后赋予它的变量名称将被视为常量指针(其值无法更改)

This restriction is imposed by the compiler because it thinks if you change the value arr then there no way to ensure the accuracy of the program because the base address has been modified

但是如果您真的想使用指针,请检查这些代码:

int main() {
int arr[] = {1,2,3,0};
int *ptr = arr;

while(*ptr != 0) {
printf("%i ",*ptr);
ptr++; // or ++ptr;
}
return 0;
}

输出: 1 2 3

int main() {
int *arr = (int*)malloc(4*sizeof(int));
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 0;

while(*arr != 0) {
printf("%i ",*arr);
arr++;
}
return 0;
}

输出: 1 2 3

我希望我已经说清楚了。如有任何疑问,欢迎。

关于c - 在 C 中打印数组元素的地址时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084084/

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