Having a function change the value a pointer represents in C

后端 未结 6 1234
攒了一身酷
攒了一身酷 2020-12-06 01:16

I have a main function that has a char, I am attempting to pass a pointer to that char into a function and have it change it from A to

6条回答
  •  温柔的废话
    2020-12-06 01:49

    C copies pointers that are passed in to functions as parameters. So inside the function you are manipulating a copy of the pointer, not the pointer itself. When the function exits, the pointer if it was changed as in

     while (p++)  if (*p = '\0') break;  //example
    

    will return to its previous value and the copy will be destroyed. The object of memory location the pointer points to may be changed and that is the whole idea behind pass by reference. A common mistake is trying to null a pointer inside of a function and then discovering it not being null upon return from the function. On some systems you get back the pointer pointing to garbage or bad memory locations that crash your program when you try to read from or write to the variable.

    void f(char* s)
    {
      /* code stuff */
    ...
    s = NULL;
    ...
    return;
    }
    

    upon return from f now s = ? (previous value , NULL, or GARBAGE ) This happens most often with variables passed to functions defined in separate modules that take values by reference, or across execution contexts (like threads or shared memory between processes).

提交回复
热议问题