Mukul RoyHello C Developers! π Let's test our debugging skills today. Iβve written a small piece of code that...
Hello C Developers! π
Let's test our debugging skills today. Iβve written a small piece of code that is supposed to swap two strings using pointers. However, it's not behaving as expected (or it might even crash!).
void swap_strings(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
int main() {
char *p1 = "Game";
char *p2 = "Changer";
printf("Before Swap: p1 = %s, p2 = %s\n", p1, p2);
// Attempting to swap
swap_strings(&p1, &p2);
printf("After Swap: p1 = %s, p2 = %s\n", p1, p2);
return 0;
}
The Challenge:
Will this code compile and run successfully?
Is there a hidden bug or a potential Segment Fault?
If you had to rewrite this to be safer, what would you change?
I see many beginners and even intermediate coders struggle with char * vs char [] when passing to functions.
Drop your answers in the comments! Letβs see who explains it the best. π