0

This is my main.c:

#include <stdio.h>

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

int main(int argc, char **argv) {
    char *stuff;
    changeStuff(stuff);
    printf(stuff);
    return 0;
}

When I build this, I get this warning:

warning: ‘stuff’ is used uninitialized in this function [-Wuninitialized]

When I run this program, nothing is printed.

Since it does not seem possible to define a char* with no value after it has been declared, how do I change the value of a char* passed to a function?

P.P
  • 117,907
  • 20
  • 175
  • 238
Username
  • 3,463
  • 11
  • 68
  • 111

1 Answers1

2

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?

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
  • One question. Is passing by reference -- &stuff -- the same as passing a pointer to a pointer? – Username Jan 07 '17 at 21:41
  • 1
    there is no pass-by-reference in C (only in C++) – artm Jan 07 '17 at 21:41
  • 2
    C doesn't have pass by reference at all. `&stuff` is still passed by value (except that you can use that value to modify its pointee). – P.P Jan 07 '17 at 21:42
  • Ah, it's pass by address. In this case, is there a difference between what is represented by `char **stuff` and `&stuff`? – Username Jan 07 '17 at 22:02
  • `char *stuff` is a pointer. `&stuff` is the address of the pointer itself. `char **stuff` is pointer to a pointer. The function writes to `*stuff` so it changes the pointer, because it was passed the *address* of a pointer. – Weather Vane Jan 07 '17 at 22:19