arrayscpointerspass-by-referencestring-literals

Why cant I modified the char array when passing it as an argument to the function and assigning it a new value?


void changeName(char* name) {
    //other action

    //strcpy(name, "String"); -- this working
    name = "Marcus"; //       -- this not working

}

int main() {
    char name[10] = "Jeremy";
    printf("%s\n", name);

    changeName(name); 
    //Aspected result: Marcus
    //Actual result: Jeremy

    printf("%s\n", name);
    return 0;
}

In the provided source code, when attempting to modify the char name[50] array from 'Jeremy' to 'Marcus' by passing it to a function, I encountered an issue with the assignment. I tried two methods:

Method 1:

strcpy(name, "String");

Method 2:

name = "Marcus";

But in somehow, The first method worked while the second did not. Why is this happening and how can i resolve this?


Solution

  • In the example where you are assigning to the pointer, you are merely changing what the local char pointer name points to so that it points to a string literal "Marcus". This has no effect on the array in main.

    In the example using strcpy, you modify the data the pointer points to. Notably, since you don't pass changeName any information on how large the char array is that the pointer points to, you have a potential buffer overflow bug.

    This can be overcome using strncpy.

    void changeName(char *name, size_t max) {
        strncpy(name, "String", max-1);
        name[max] = '\0';
    }
    

    Now we'd want to call this as follows. This cannot overflow name.

    int main() {
        char name[10] = "Jeremy";
    
        printf("%s\n", name);
        changeName(name, sizeof(name) - 1); 
        printf("%s\n", name);
    
        return 0;
    }