您好,我是编程新手,我对指针有一个小疑问
#include<iostream>
using namespace std;
int main()
{
int myAge = 16;
int* agePtr = &myAge;
cout << "address of pointer" << agePtr << "Data at memory address" << *agePtr << endl;
int badNums[5] = {4, 13, 14, 24, 34};
int* numArrayPtr = badNums;
cout<< "address" << numArrayPtr << "value" << *numArrayPtr << endl;
numArrayPtr++;
cout<< "address" << numArrayPtr << "value" << *numArrayPtr << endl;
return 0;
}
在第一种情况下,当我指向一个整数时,我使用
&myAge
其中 如果我使用&badNums
编译器,则递增数组的第二种情况 返回一个错误,但是如果我使用badNums
它的编译为什么应该 在第二种情况下我们使用badNums
而不是&badNums
?如何使用指针递增整数值?
最佳答案
根据 C++ 规则,数组隐式衰减为指针。有很多implicit conversions在 C++ 中,这是其中之一。将数组分配给指针时,它会为您提供指向数组中第一个元素的指针。
获取数组的地址 (&badNums
) 将产生一个指向数组的指针,而不是指向第一个元素的指针。数组指针稍微复杂一些,并且在类型中对数组的大小进行编码。该赋值的正确类型为 int (*numArrayPtr)[5] = &badNums;
,其中 numArrayPtr
是指向 5 int
数组的指针>s.
要通过指针递增值指针,您必须首先使用运算符 * 取消引用该指针,就像您想要读取或写入该值一样。它看起来像 (*numArrayPtr)++;
。
关于c++ - int 和数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45239576/