增加指针的内容
Increment content of pointer
我试图在 C 中递增一个值并 return 旧值,我正在使用指针来实现。问题是即使我使用指针,新值仍然是 0。
#include <stdio.h>
#include <stdlib.h>
int increment (int *mem) {
int tmp;
tmp = *mem;
*mem++;
return tmp;
}
int main () {
int a = 0;
printf("The old value of a is \t %d", increment(&a));
printf("The new value of a is \t %d", a);
}
现在,当我 运行 使用此方法时,我得到了相同的 a 值,即 0;我在第二个 printf 中期待 1。我不知道我在这里做错了什么。
改变这个
*mem++;
至此
(*mem)++;
问题出在运营商的优先级上。您可能想阅读有关 C Operator precedence.
的内容
那么,您的代码是做什么的?它增加了指针的值,因为 ++
运算符首先被激活,然后 *
被激活,没有实际效果。
因此,您的代码调用 undefined behavior,因为您访问(并最终写入)无效的内存位置,因为指针在值写入之前递增。
也许你漏掉了一些括号?
#include <stdio.h>
#include <stdlib.h>
int increment (int *mem) {
int tmp;
tmp = *mem;
(*mem)++; // problem was here.
return tmp;
}
int main (){
int a = 0;
printf("The old value of a is \t %d", increment(&a));
printf("The new value of a is \t %d", a);
}
除了其他人发布的关于运算符优先级的内容之外,如果您传递一个指向要递增的 int 的指针,则没有理由通过 tmp
return int 的副本].您将可以在函数外访问 mem
中的值。
#include <stdio.h>
#include <stdlib.h>
void increment (int *mem) {
(*mem)++;
}
int main () {
int a = 0;
printf("The old value of a is \t %d", a);
increment(&a);
printf("The new value of a is \t %d", a);
}
我试图在 C 中递增一个值并 return 旧值,我正在使用指针来实现。问题是即使我使用指针,新值仍然是 0。
#include <stdio.h>
#include <stdlib.h>
int increment (int *mem) {
int tmp;
tmp = *mem;
*mem++;
return tmp;
}
int main () {
int a = 0;
printf("The old value of a is \t %d", increment(&a));
printf("The new value of a is \t %d", a);
}
现在,当我 运行 使用此方法时,我得到了相同的 a 值,即 0;我在第二个 printf 中期待 1。我不知道我在这里做错了什么。
改变这个
*mem++;
至此
(*mem)++;
问题出在运营商的优先级上。您可能想阅读有关 C Operator precedence.
的内容那么,您的代码是做什么的?它增加了指针的值,因为 ++
运算符首先被激活,然后 *
被激活,没有实际效果。
因此,您的代码调用 undefined behavior,因为您访问(并最终写入)无效的内存位置,因为指针在值写入之前递增。
也许你漏掉了一些括号?
#include <stdio.h>
#include <stdlib.h>
int increment (int *mem) {
int tmp;
tmp = *mem;
(*mem)++; // problem was here.
return tmp;
}
int main (){
int a = 0;
printf("The old value of a is \t %d", increment(&a));
printf("The new value of a is \t %d", a);
}
除了其他人发布的关于运算符优先级的内容之外,如果您传递一个指向要递增的 int 的指针,则没有理由通过 tmp
return int 的副本].您将可以在函数外访问 mem
中的值。
#include <stdio.h>
#include <stdlib.h>
void increment (int *mem) {
(*mem)++;
}
int main () {
int a = 0;
printf("The old value of a is \t %d", a);
increment(&a);
printf("The new value of a is \t %d", a);
}