简体   繁体   中英

Passing String Address As Parameter To Pointer To Pointer To Char Function

While I was doing a online quiz ( http://www.mycquiz.com/ ), I came to this question:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void myfunc(char** param){
    ++param;
}
int main(){
    char* string = (char*)malloc(64);
    strcpy(string, "hello_World");
    myfunc(&string);
    printf("%s\n", string);
    // ignore memory leak for sake of quiz
    return 0;

My first answer choice was that the string would get modified, whch didn't happen, and I am puzzled why not? Isn't he passing the address of the literal? Also a train of thought came to me that how would these situation vary?

void myfunc(char* param){
        ++param;
}
int main(){
    char* string = (char*)malloc(64);
    strcpy(string, "hello_World");
    myfunc(string);

void myfunc(char* param){
    ++param;
}
int main(){
    char string[12];
    strcpy(string, "hello_World");
    myfunc(string);

None of them seems to actually change the passed string. So if I do need to modify the string how do I pass it by reference?

Thanks.

In all cases, you are passing a pointer to something to a C function, modifying the pointer, not its contents, and then printing the string in main() . When you pass a pointer, a copy of it is made, so the version you modify in the function does not affect the value in main() . That is why you will not see any change in the string unless you start to modify the contents of the pointer.

If you wish to make changes to the string:

void myfunc(char** param){
        ++(*param);
}

will print ello_World since it will increment the address used by main() to point to the memory containing the string.

void myfunc(char* param){
    ++(*param);
}

will print iello_World since it will modify the first char in the actual piece of memory containing the string.

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