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 for everyone, or is it?
The Code:
include
// Function to swap two string pointers
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:
Memory Safety: Does this code lead to a Segmentation Fault?
Pointer Logic: Are we swapping the actual content or just the memory addresses?
Best Practice: Why is using char *p = "String" considered risky compared to char p[] = "String" in this context?
Iβve seen many beginners struggle with pointer-to-pointer logic and String Literals. Let's discuss in the comments! π
Top comments (3)
You need to learn to use Markdown and format your code correctly. To begin and end a code block, use 4 back-ticks on a line by themselves. For inline code, encode it between single back-ticks. Otherwise, your article is too hard to read.
Thanks for the feedback! You're absolutely rightβproper formatting is essential for readability. I've updated the post with the correct code blocks and markdown. Appreciate you pointing that out and helping me improve the quality of my articles! π
It's still wrong.