为什么值不同?C++ 指针 [英] Why are the values different? C++ pointer

查看:46
本文介绍了为什么值不同?C++ 指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌上搜索了一个解决方案来找出 C++ 中数组的长度.我找到的解决方案之一是这个

I was googling a solution to find out the length of an array in C++. One of the solutions I found is this

int arr[] = {1,2,3,4,5,6};
int size = *(&arr+1)-arr; //size is the length of the array

我在 &arrarr 之间感到困惑,因为它们都给出了数组的基地址.再次谷歌搜索,发现 &arr + 1 给出了不属于数组的下一个内存块的地址,其中 arr + 1 给出了下一个元素的地址数组.

I was confused between &arr and arr since both give the base address of the array. Googled again and found that &arr + 1 gives the address of next block of memory that is not part of the array where arr + 1 gives the address of next element in the array.

我编写了以下代码来测试&arrarr 之间的区别:

I have written the following code to test out the difference between &arr and arr:

int arr[] = {1,2,3,4,5,6};
printf("value of &arr + 1 - &arr = %d\n", &arr + 1 - &arr);
printf("value of *(&arr + 1) - arr = %d\n", *(&arr + 1) - arr);

第一个 printf 的答案是 1 而第二个 printf 给出 6.这是让我困惑的部分:既然 &arrarr 都持有同一个数组的基地址,为什么结果会不同?

The answer to the first printf is 1 where as the second printf gives 6. This is the part that confuses me: Since both &arr and arr hold the base address of the same array, why are the results different?

推荐答案

既然&arr"和arr"都持有同一个数组的基地址,为什么结果不一样?

Since both "&arr" and "arr" hold the base address of the same array, why are the results different?

因为类型不同.指针运算受指针类型的影响,更具体地说,受指向对象的类型影响.

Because the type is different. Pointer arithmetic is affected by the type of the pointer, and more specifically, the type of the pointed object.

&arr 是一个指向 6 个 int 数组的指针.将 1 添加到下一个由 6 个整数组成的数组中(如果它是数组数组的元素).

&arr is a pointer to an array of 6 int. Adding 1 to that increments to the next array of 6 ints (if it was an element of an array of arrays).

arr 虽然是一个数组,但在使用它的值时会衰减到指向数组第一个元素的指针,例如在指针算术表达式中.衰减后的值是一个指向 int 的指针,然后加 1 将指针移到下一个整数.

arr, although is an array, decays to pointer to the first element of the array when its value is used, such as in the pointer arithmetic expression. The decayed value is a pointer to an int and adding 1 to that moves the pointer to the next integer.

附言您可以使用 std::size 代替.或 std::extent C++17 之前的版本.或者 sizeof arr/sizeof *arr C++11 之前.

P.S. You can use std::size instead. Or std::extent pre-C++17. Or sizeof arr / sizeof *arr pre-C++11.

*(&arr + 1) - arr 可能有效,但从技术上讲,它是通过后尾指针(指向不存在的对象)间接进行的,这通常是未定义的行为.考虑到该值仅用于衰减到指针,我不确定该规则是否可能有一些例外.

*(&arr + 1) - arr probably works, but technically indirects through a past-the-end pointer (to an object which does not exist), which is typically undefined behaviour. I'm not sure whether there might be some exception to the rule considering the value is only used to decay to a pointer.

这篇关于为什么值不同?C++ 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆