试图理解C中指针的行为,我对以下内容感到有点惊讶(下面的示例代码):
#include <stdio.h>
void add_one_v1(int *our_var_ptr)
{
*our_var_ptr = *our_var_ptr +1;
}
void add_one_v2(int *our_var_ptr)
{
*our_var_ptr++;
}
int main()
{
int testvar;
testvar = 63;
add_one_v1(&(testvar)); /* Try first version of the function */
printf("%d\n", testvar); /* Prints out 64 */
printf("@ %p\n\n", &(testvar));
testvar = 63;
add_one_v2(&(testvar)); /* Try first version of the function */
printf("%d\n", testvar); /* Prints 63 ? */
printf("@ %p\n", &(testvar)); /* Address remains identical */
}
Run Code Online (Sandbox Code Playgroud)
输出:
64
@ 0xbf84c6b0
63
@ 0xbf84c6b0 …Run Code Online (Sandbox Code Playgroud) 以下是2个代码示例:
int k,j=1;
int x[4]={5,14,25,47};
k = x[j] + ++j;
printf("%d, %d",j,k);
Run Code Online (Sandbox Code Playgroud)
显示警告 - “对 'j' 的操作可能未定义”但输出为:2, 16
然后我尝试了这个:
int k,j=1;
int x[4]={5,14,25,47};
k = x[j] +++j;
printf("%d, %d",j,k);
Run Code Online (Sandbox Code Playgroud)
这不会发出任何警告,但输出有点令人困惑。输出- 1,15 为什么 j 在第二种情况下没有增加?