|
发表于 2019-8-19 08:13:47
|
显示全部楼层
本帖最后由 Python.爱好者 于 2019-8-19 08:15 编辑
- #include <stdio.h>
- int main()
- {
- int arr[] = {11,12,13,14,15};
- int *ptr = arr;
- *(ptr++) += 100;
- printf("%d %d\n",*ptr,*(++ptr));
-
- return 0;
- }
复制代码
这段代码存在误导性的一点在于printf函数。
printf函数的原型是
int __cdecl printf(const char * __restrict__ _Format,...);
注意__cdecl:
__cdecl 是C Declaration的缩写(declaration,声明),表示C语言默认的函数调用方法:所有参数从右到左依次入栈,这些参数由调用者清除,称为手动清栈。被调用函数不会要求调用者传递多少参数,调用者传递过多或者过少的参数,甚至完全不同的参数都不会产生编译阶段的错误。——百度百科
因此,我的理解是,(1)*(++ptr)入栈,ptr更新为arr+2,对应的数是13。(2)接下来*ptr入栈,对应的数依然是13。
证据是把*(++ptr)替换为*(ptr++)输出13 12。
而把printf的参数交换位置时输出12 13。
最后把printf这句话替换为
- int p,pp;
- p=*ptr,pp=*(++ptr);
- printf("%d %d",p,pp);
复制代码
或
- int p=*ptr,pp=*(++ptr);
- printf("%d %d",p,pp);
复制代码
时输出12 13,因为逗号运算符以及变量的定义是从左到右进行计算的。
所有代码均为本人在dev-c++上测试。 |
|