增加指针的内容

时间:2015-07-17 12:56:40

标签: c pointers operators

我试图在C中增加一个值并返回旧值,我正在使用指针。问题是即使我使用指针,新值仍为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);
}

现在,当我运行此方法时,我得到的值为0;我期待在第二个printf中有1个。我不知道我在这里做错了什么。

3 个答案:

答案 0 :(得分:9)

更改此

*mem++;

到这个

(*mem)++;

问题在于运营商的优先权。您可能需要阅读C Operator precedence

那么,您的代码有什么作用?它会增加指针的值,因为++运算符首先被激活,然后*被激活,没有实际效果。

因此,您的代码调用undefined behavior,因为您访问(并最终写入)无效的内存位置,因为指针在写入值之前递增。

答案 1 :(得分:5)

也许你错过了一些括号?

#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);
}

答案 2 :(得分:0)

除了其他人发布的关于运算符优先级的内容之外,如果要传递指向要递增的int的指针,则没有理由通过tmp返回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);
}
相关问题