你能解释一下 *ptr++ 和 *(++ptr) 之间的区别吗?

标签 c arrays pointers

Possible Duplicate:
Pointer Arithmetic: ++*ptr or *ptr++?

我不明白有什么区别?下面是实现 *ptr++ 的代码示例

#include <stdio.h>
int my_array[] = {1,23,17,4,-5,100};
int *ptr;
int main(void)
{
int i;
ptr = &my_array[0]; /* point our pointer to the first
element of the array */
printf("\n\n");
for (i = 0; i < 6; i++)
{
printf("my_array[%d] = %d ",i,my_array[i]);
printf("ptr + %d = %d\n",i, *ptr++);

}
return 0;
}

输出为

my_array[0] = 1 ptr + 0 = 1
my_array[1] = 23 ptr + 1 = 23
my_array[2] = 17 ptr + 2 = 17
my_array[3] = 4 ptr + 3 = 4
my_array[4] = -5 ptr + 4 = -5
my_array[5] = 100 ptr + 5 = 100

当您将第二个 printf 语句更改为 printf("ptr + %d = %d\n",i, *(++ptr)); 时 这成为输出:

my_array[0] = 1 ptr + 0 = 23
my_array[1] = 23 ptr + 1 = 17
my_array[2] = 17 ptr + 2 = 4
my_array[3] = 4 ptr + 3 = -5
my_array[4] = -5 ptr + 4 = 100
my_array[5] = 100 ptr + 5 = -1881141248

请有人详细解释一下其中的区别,以便我能够理解。

最佳答案

一个在获取指针指向的内容之前递增指针,另一个在从指针获取之后递增。

在第二个示例中,您在最后一次迭代中已经越过了数组的末尾,并且您正在打印(可能)紧随数组(或一些随机垃圾)之后的内存位置中的指针

关于你能解释一下 *ptr++ 和 *(++ptr) 之间的区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999058/

相关文章:

c - 为什么 node* root = malloc(sizeof(int)) 分配 16 个字节的内存而不是 4 个?

c - 在 c 中生成阿姆斯特朗数到第 n 个数不起作用

关于从指针类型传递参数的 CodeBlocks 项目

c ) make error& link problem : i386:x86-64 architecture of input file, 与 i386 输出不兼容

arrays - 用于 Rust 结构的实现

javascript - 在javascript中填充数组,这两种方法有什么区别?

C++ 参数是指向常量对象的指针,但未返回更新的对象?

c - 查找具有特定总和(+ve 或 -ve)的所有连续子集,其中子集可以包含正整数和负整数

php保留一个数组复选框

c++ - C++中的字符串指针