如何在函数中给指针赋值

指针在局部函数中也是值传递.因此修改指针本身的值,是不会在局部函数外其效果.

#include <iostream>

inline static void assignPtr1(int *p) {
    int n = 2;
    p = &n;
}

inline static void assignPtr2(int *p) {
    int n = 2;
    *p = n;
}

int main() {
    int v = 1;
    int *p = &v;

    std::cout << "ptr p : " << *p << std::endl;
    assignPtr1(p);
    std::cout << "change ptr p by p=&n : " << *p << std::endl;


    int *q = &v;

    std::cout << "ptr q : " << *q << std::endl;
    assignPtr2(q);
    std::cout << "change ptr q by *q=n : " << *q << std::endl;
    return 0;
}
ptr p : 1
change ptr p by p=&n : 1
ptr q : 1
change ptr q by *q=n : 2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.