Can I change an initialized char pointer via function?

前端 未结 1 1563
野的像风
野的像风 2021-01-29 05:33

This is my main.c:

#include 

void changeStuff(char *stuff){
    stuff=  \"Hello everyone\";
}

int main(int argc, char **argv) {
            


        
相关标签:
1条回答
  • 2021-01-29 05:39

    In C, function arguments are passed-by-value. In order to modify a pointer value, you need to pass a pointer to the pointer, like:

    #include <stdio.h>
    
    void changeStuff(char **stuff){
        *stuff=  "Hello everyone";
    }
    
    int main(int argc, char **argv) {
        char *stuff;
        changeStuff(&stuff);
        printf("%s\n", stuff);
        return 0;
    }
    

    Note that it's not a good idea to directly pass user-defined values to printf(). See: How can a Format-String vulnerability be exploited?

    0 讨论(0)
提交回复
热议问题