Oğu*_*lan -2 c c++ arrays pointers
那时我正在为我的考试而学习?在网上看到了这个。我的问题是数组不是基本上是 c 中的常量指针(所以有错误)?起初我想得到一个关于这个“b+=2”的错误,但没有。
int func ( int b[])
{
b +=2;
printf("%d",*b);
}
int main()
{
int arr[]={1,2,3,4};
func(arr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(这个程序的输出是 3 btw)
不是数组基本上是c中的常量指针
不,他们不是。数组是连续的对象序列。指针是通过存储内存地址来引用另一个对象的对象。
为什么我可以更改数组
Run Code Online (Sandbox Code Playgroud)b +=2;
b不是数组。b是一个指针。最初,您传递一个指向数组第一个元素的指针arr。将指针加 1 会将其更改为指向数组的连续元素。添加 2 将其更改为指向第二个连续元素。从第一个元素开始,第二个连续的元素是索引为 2 的元素,在这种情况下它的值为 3。这种指针算法就是为什么可以使用指针迭代数组元素的原因。
但它是使用通常与数组关联的语法声明的
函数参数不能是数组。您可以将参数声明为数组,但该声明被调整为指向数组元素的指针。这两个函数声明在语义上是相同的:
int func ( int b[]); // the adjusted type is int*
int func ( int *b );
Run Code Online (Sandbox Code Playgroud)
它们都声明了一个函数,其参数是指向 的指针int。这种调整并不意味着数组是指针。这种调整是对数组隐式转换为指向第一个元素的指针的规则的补充——这种转换称为衰减。
请注意,参数声明是发生这种调整的唯一情况。例如在变量声明中:
int arr[]={1,2,3,4}; // the type is int[4]; not int*
// the length is deduced from the initialiser
int *ptr; // different type
Run Code Online (Sandbox Code Playgroud)
另请注意,调整仅发生在复合类型的“顶级”级别。这些声明是不同的:
int funcA ( int (*b)[4]); // pointer to array
int funcB ( int **b ); // pointer to pointer
Run Code Online (Sandbox Code Playgroud)
PS 您已将函数声明为 return int,但未能提供 return 语句。在 C++ 中这样做会导致程序的未定义行为。