Hello guys,
I have this function:

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

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?

Thanks

Recommended Answers

All 3 Replies

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...

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

Thanks

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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.