Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string modifying function: return void or char*?

For example:

void foo1(char *buffer) {
    buffer[0] = 'a';
}

char *foo2(char *buffer) {
    buffer[0] = 'a';
    return buffer;
}

When i want to modify a string I could do:

mystr[] = "foobar";
foo1(mystr);
printf("%s",mystr);

or using the return value:

mystr[] = "foobar";
char *mystr2;
mystr2 = foo2(mystr);
printf("%s",mystr2);

I'm a bit confused by the second way: mystr and mystr2 are pointing to different locations but holding the same string. I thought foo2 will copy the address of the modified mystr to mystr2 when returning. What happens instead?

The second question is: Which way of modifying a string is more standard?

like image 307
Rick Mitchsel Avatar asked Dec 13 '25 00:12

Rick Mitchsel


1 Answers

Which way of modifying a string is more standard?

Standard C string functions declared in the header <string.h> usually return pointer to the target string. This allows to chain string functions together. For example relative to your second function definition you could write

printf("%s", foo2(mystr));

and the statement outputs the modified source string.

In this code snippet

char mystr[] = "foobar";
char *mystr2;
mystr2 = foo2(mystr);
printf("%s",mystr2);

the character array mystr[] passed to the function as an argument is implicitly converted to pointer to its first character. And the same address is returned from the called function that is the pointer to the first character of the array. Thus after this statement

mystr2 = foo2(mystr);

the pointer mysstr2 also points to the first character of the character array mystr.

The function printf can be called either like

printf("%s",mystr);

or like

printf("%s",mystr2);

because the same address is passed to the function in the both cases and again the character array passed to the function printf in the first case is implicitly converted to pointer to its first character.

like image 192
Vlad from Moscow Avatar answered Dec 14 '25 14:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!