user997112
user997112

Reputation: 30615

char "string" not updating in function

I have a function which looks like:

void myFunc(char* myString, char* const buf, int startPos){
    myString = &buf[startPos];
    std::cout << myString << std::endl;     //This outputs fine
}

. . . .

char* myString = 0;
.
.
myFunc(myString, buf, startPos);
std::cout << myString << std::endl;         //This doesnt output anything

Why doesn't printing out the string work after I have made the function call?

Upvotes: 0

Views: 457

Answers (3)

haccks
haccks

Reputation: 106042

When you call

myFunc(myString, buf, startPos);  

myString is copied to the function parameter. Any changes to the pointer myString does not change the pointer myString in main.

Either use char **mystring in function parameter or pass myString by reference.

void myFunc(char&* myString, char* const buf, int startPos){...}

Upvotes: 4

TripeHound
TripeHound

Reputation: 2960

If you want to modify something in a function, you have to pass a pointer to that "thing"... in this case, your "thing" is a "pointer-to-char" so you need to pass in a "pointer-to-'pointer-to-char'", so:

void myFunc(char** myString, char* const buf, int startPos){
    *myString = &buf[startPos];
    std::cout << *myString << std::endl;     //This outputs fine
}

and call it with:

myFunc(&myString, buf, startPos);

The &myString takes the address of your "pointer-to-char" which will allow the function to modify it; inside the function, you need the extra *s to dereference this address and get to the value you want to change.

Upvotes: -1

Easton
Easton

Reputation: 265

Why not make the function return the value of mystring?

char* myFunc(char* myString, char* const buf, int startPos){
    myString = &buf[startPos];
    std::cout << myString << std::endl;     //This outputs fine
    return myString;
}

Then print the value:

std::cout << myFunc(myString, buf, startPos) << std::endl;

Or, you could do:

myString = myFunc(myString, buf, startPos);
std::cout << myString << std::endl;

Upvotes: 0

Related Questions