我的代码是:
main()
{
static int arr[]={97,98,99,100,101,102,103,104};
int *ptr=arr+1;
print(++ptr,ptr--,ptr,ptr++,++ptr);
}
print(int*a,int*b,int*c,int*d,int*e)
{
printf("%d %d %d %d %d",*a,*b,*c,*d,*e);
}
输出为:100 100 100 99 100
我无法理解这个问题。
请有人向我解释一下这段代码及其输出。
谢谢。
最佳答案
首先,这一行包含未定义的行为
print(++ptr,ptr--,ptr,ptr++,++ptr);
因为它多次使用属于具有副作用的表达式一部分的变量,但没有达到 sequence point .
In the code static keyword is used so i thought that each time it would take a different input.
在此示例中,存在或不存在 static
关键字没有任何区别,因为代码从不打印指针的值,仅打印该指针指向的内存内容。
您可以通过将每个具有副作用的表达式移动到单独的行来删除未定义的行为,如下所示:
static int arr[]={97,98,99,100,101,102,103,104}; // static can be removed
int *ptr=arr+1; // Start at index 1
printf("%d\n", *++ptr); // Move to index 2, prints 99
printf("%d\n", *ptr--); // Print 99, move to index 1
printf("%d\n", *ptr); // Print 98, stay at position 1
printf("%d\n", *ptr++); // Print 98, move to position 2
printf("%d\n", *++ptr); // Move to position 3, print 100
( demo )
现在输出不同(并且正确):
99
99
98
98
100
这是您应该根据预增量/减量和后增量/减量运算符的语义获得的输出。
关于具有静态和指针的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20264407/