C + + pointer parameter assignment problem

Source: Internet
Author: User

Today, there is a problem with the question of assigning a pointer to a function in C + +. The following phenomena can be seen first:

void Test (int *p) {    p = NULL;} int main (int argc, char *argv[]) {    qcoreapplication A (argc, argv);    int *t, y = ten;    t = &y;    Test (t);    return a.exec ();}

  

I was a little surprised at the result, I always thought that the pointer will be passed, and the pointers are also changed, but the pointer is also a variable, if we want to change it, we must find its address in memory, that is, the address of the pointer. In other words, in a function, if the address of the pointer is assigned, in fact, the original pointer can not be changed!

void Test (int **p) {    *p = NULL;} int main (int argc, char *argv[]) {    qcoreapplication A (argc, argv);    int *t, y = ten;    t = &y;    Test (&t);    return a.exec ();}

  

In addition, assigning values by reference can also solve this problem:

void Test (int &p) {    int n = 9;    p = N;} int main (int argc, char *argv[]) {    qcoreapplication A (argc, argv);    int T, y = ten;    t = y;    Test (t);    return a.exec ();}

  

In addition, you can modify what the pointer points to, instead of modifying the pointer address, or you can change the content.

Example 1:

void Test (int *p) {    int n = 9;    *p = n;} int main (int argc, char *argv[]) {    qcoreapplication A (argc, argv);    int *t, y = ten;    t = &y;    Test (t);    return a.exec ();}

  

Example 2:

void Test (int *p) {    int n = 9;    *p = n;} int main (int argc, char *argv[]) {    qcoreapplication A (argc, argv);    int T, y = ten;    t = y;    Test (&t);    return a.exec ();}

  

C + + pointer parameter assignment problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.