Username
Username

Reputation: 3663

Can I change an initialized char pointer via function?

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?

Upvotes: 0

Views: 1081

Answers (1)

P.P
P.P

Reputation: 121407

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?

Upvotes: 2

Related Questions