为什么在递增后使用 [] 运算符访问指针数组会返回错误地址的当前内存位置
Why does accessing pointer array using [] operator after increment the current memory position of return bad address?
我知道使用指针算法有副作用,但我无法弄清楚这背后发生了什么
int * pointer_arr = new int [ 3 ] { 10, 11, 12 };
std::cout << * pointer_arr ++ << std::endl; // output 10 then increment
std::cout << ++ * pointer_arr << std::endl; // access then increment => output 12
++ * pointer_arr;
std::cout << pointer_arr [ 0 ] << std::endl; // should output 13
std::cout << pointer_arr [ 1 ] << std::endl; // should output 11
std::cout << pointer_arr [ 2 ] << std::endl; // should output 12, but this output 0 instead
delete [] pointer_arr;
// output
// also, it miss another element of 11
10
12
13
13
12
0
另外,如果我尝试用括号包装第一个
std::cout << ( * pointer_arr ) ++ << std::endl;
输出将是
10
12
13
13
11
12
这就是我期望上面会打印出来的。然后,如果我在输出 12 的行之后添加另一行移动到下面的第二个索引,
std::cout << * ++ pointer_arr << std::endl;
这种情况会发生
10
12
11
12
12
12
-1342177820
我正在尝试理解指针的基本原理,我知道对指针进行算术运算有副作用,但这让我感到困惑。请帮助我解释为什么在上面的某些操作或指针算术之后使用 [] 运算符输出数组的最后一个索引会导致意外结果以及括号环绕指针和没有括号环绕之间的差异。
表达式* pointer_arr ++
将增加指针,而不是它指向的元素。这意味着它将不再指向数组中的第一个元素,而是指向第二个元素。这也意味着pointer_arr[2]
将超出界限,因为它是三元素数组的第四个元素。
然后您将修改后的指针传递给delete[]
.必须将原始指针传递给 delete[]
。
取消引用和delete[]
都将导致未定义的行为。
这是运算符优先级的问题,其中后缀++
运算符的优先级高于取消引用运算符*
。这意味着* pointer_arr ++
实际上是* (pointer_arr ++)
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- C++中函数的向量返回类型引发错误
- 有人知道为什么在开关中使用stoi函数会返回恒定的错误吗
- glad 导致 glfwSwapBuffers 返回错误消息
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- QNX Momentics: GoogleMock - 返回有价值,在函数中返回 void 错误
- 我的模板类方法返回错误类型?
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 替换WCHAR_T错误返回存储地址
- 错误:void 值未被忽略,因为它应该被忽略,错误:返回语句具有值
- 带有值的递归阶乘错误返回语句,在函数中返回 'void' [-fallowive]
- 存储在静态常量整数 (C++) 中的对数函数的错误返回值
- 更丰富的错误返回消息用于提升::精神::qi 解析
- C++初级逻辑错误-返回0
- 由于进程很多,pthread_create的错误返回代码是 35 错误,我用过pthread_exit应该杀死线程不是吗?
- c++错误处理返回值错误返回
- systememerror:没有异常集的错误返回