Reputation: 53
I'm kind of new to using pointers in C. So I've been trying to get used to them. So what I wanted to do was swap the first character of two strings using pointers. This is what I came up with
#include <stdio.h>
void swap_first_char(char *s1, char *s2) {
char temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int main() {
char *str1 = "ASTRING";
char *str2 = "BSTRING";
swap_first_char(str1,str2);
printf("str1 = %s, str2 = ‰s\n", str1, str2);
return 0;
}
So, this is my understanding right now. str1 and str2 hold the address of the first character of "ASTRING" and "BSTRING".
So when I pass them to the swap_first_char(char*, char*);
function, now s1 holds the address of the first character of string "ASTRING", and s2 holds the address of the first character of the string "BSTRING". So I could dereference them and swap them to swap the first character of both the strings right?
But I keep getting a segmentation fault on executing this piece of code. If someone can tell me why it is so, I'd be greatful. Thankyou ^_^
Upvotes: 2
Views: 102
Reputation: 4247
Expanding this to an answer where I can use some code: string constants - quoted strings - are often (but not required to be) readonly, and in a sense it's a dirty trick that the compiler allows you to assign one of them to a char *
(which would allow you to write to it) instead of const char *
(which would forbid it).
Replacing
char *str1 = "ASTRING";
char *str2 = "BSTRING";
with
char str1[] = "ASTRING";
char str2[] = "BSTRING";
does in fact fix the problem (as tested on my x86 system with gcc). In the latter case, the compiler is allocating the full array of the string (plus the NUL byte), while in the former it's just a pointer to the bytes allocated elsewhere.
Upvotes: 1