简体   繁体   中英

Creating a pointer, pass a pointer, pass an address of a pointer

What is a difference between these two codes?

Can anybody explain in to me like: #1 do, #2 do, #3 do , please?

I have some ideas what these codes do, but I am not sure about it.

void test(char *msg) {
/*3*/    msg = new char[5];
}

int main() {
/*1*/    char *msg;
/*2*/    test(msg);
}

// I think
// #2 Pass the pointer
// #3 Allocates 5 bytes char in address where the pointer points
void test(char **msg) {
/*3*/    *msg = new char[5];
}

int main() {
/*1*/    char *msg;
/*2*/    test(&msg);
}

// I think
// #2 Pass the address to the 4 bytes memory block where the pointer is stored
// #3 Allocates 5 bytes char to the previous 4 bytes + allocates new 1 byte

Thanks a lot!

I suppose you are confused by too many pointers. Pointers are scary for a reason, but in many regards they are like any other variable.

Modifying a pointer passed by value to a function has no effect on the pointer that was passed to the function.

Reducing the scariness of your example a bit we get:

void test(std::string msg) {
    msg = std::string("Hello World");
}

int main() {
    std::string msg;
    test(msg);
    std::cout << msg;  // is still an empty string !
}



void test(std::string* msg) {
    *msg = std::string("Hello World");
}

int main() {
    std::string msg;
    test(&msg);
    std::cout << msg;  // prints hello world
}

The difference between the two examples (mine and yours) is that one is pass by value and the other is pass by reference (via a pointer).

Moreover in your code (both versions) there is a memory leak, because you do not delete the char array allocated via new .

The first:

I have a piece of paper with some meaningless scribbles on it.
I copy those scribbles to a different piece of paper, and hand it to you as a gift.
You erase the scribbles on your own paper and write down your address on it.
As you can see, my piece of paper is still only filled with scribbles, and I have no idea where you live.

The second:

I have a piece of paper with some meaningless scribbles on it.
I tell you were that piece of paper is.
You go to that place, erase the scribbles, and write down your address.
As you can see, my piece of paper now has your address on it.

(The short version: assigning to a function's non-reference parameter has no effect outside that function. There is nothing special about pointers.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM