我正在阅读《理解 c 中的指针》。
我在这里找到了一个程序。
#include<Stdio.h>
#include<conio.h>
int main()
{
static int arr[]={97,98,99,100,101,102,103,104};
int *ptr=arr+1;
printf("\nThe base Address is:%u\n",arr);
print(++ptr,ptr--,ptr,ptr++,++ptr);
return getch();
}
print(int *a,int *b,int *c,int *d,int *e)
{
printf("%d %d %d %d %d",*a,*b,*c,*d,*e);
}
该程序非常完美,我认为它必须生成以下输出:99 99 98 98 100。 但它给出以下输出:100 100 100 99 99
我无法理解请帮助我理解它。
最佳答案
除了未指定函数参数的评估顺序之外,该程序还包含多个具有未定义行为的项目:
- 它尝试在到达下一个序列点之前访问具有副作用的表达式的值(它在
print 的调用中多次执行此操作
),并且 - 它尝试使用
%u
格式说明符打印指针。
程序的编写方式可以打印任何内容,也可以不打印任何内容,甚至崩溃:这就是未定义行为的后果。
如果您希望参数按特定顺序求值,请引入临时变量,然后按顺序求值,如下所示:
#include<stdio.h>
#include<conio.h>
int main()
{
static int arr[]={97,98,99,100,101,102,103,104};
int *ptr=arr+1;
printf("\nThe base Address is:%p\n",(void*)arr);
int *tmp0 = ++ptr;
int *tmp1 = ptr--;
int *tmp2 = ptr;
int *tmp3 = ptr++;
int *tmp4 = ++ptr;
print(tmp0, tmp1, tmp2, tmp3, tmp4);
return getch();
}
print(int *a,int *b,int *c,int *d,int *e)
{
printf("%d %d %d %d %d",*a,*b,*c,*d,*e);
}
关于c - 指针给出意想不到的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19402389/