Hello guys,
I have this function:

void swap(char **a, char **b) {
char *tmp=*a;

int main() {
char *str1="aaa";
char *str2="bbb";
swap((char **)&str1, (char**)&str2);
return 0;

The program runs and really swaps the two strings.
I don't understand why we send (char**)&str1 and (char**)&str2 as an arguments.
And when doing *a in the function... what do we really get? The str1 string? or the pointer to it?

Can somebody explain what is going here?


7 Years
Discussion Span
Last Post by Narue

You have to pass the memory location that contains the pointers to the cstrings. If you think about it, it makes sense.

Here's a big hint. If you were to define your function like below

void swap(char *a, char *b);

What would happen when you call it? It would create two temp variables char *a and char *b which would store the pointers to the cstrings...now when we swap them and the functions returns char *str1 and char *str2 remain unaffected. Why? because char *str1 and char *str2 have they're own copies of the cstring pointer values...

Edited by gerard4143: n/a


Thanks gerard4143! that helped..
one thing I want to be sure about it.. what is the (char **) before the &str1 and &str2?



what is the (char **) before the &str1 and &str2?

It's an unnecessary type cast. You're forcing &str1 and &str2 into the type between parens (a type that they already have).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.