Reputation: 1
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char *a = "abcde";
char *b = "vwxyz";
char s[10];
strcpy(s,a+3);
printf("%s\n",s);
strcpy(s+2,b);
printf("%s\n",s);
return 0;
}
I am having a small issue figuring out why the second strcpy(s+2,b) outputs devwxyz.
I understand the first part because it points at a[3] and counts from then to the null character which is just 'de'.
The output is:
de
devwxyz
Basically, I don't know how to find "s+2" and I'm not sure why it is 'de' in the beginning of the final output. 'devwxyz'
Hope someone can help, thanks guys.
EDIT:
I attempted to figure it out with this piece of code and it seems the indexing didn't work for me..
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char *a = "abcde";
char *b = "vwxyz";
char s[10];
strcpy(s,a+0);
printf("%s\n",s);
strcpy(s+1,b);
printf("%s\n",s);
return 0;
}
Hope someone can explain, because the first strcpy results in abcde. And with s[1] that would be upto the letter 'b' so wouldn't it be abvwxyz? The correct result is avwxyz though.
Upvotes: 0
Views: 395
Reputation: 67195
Your code has two calls to strcpy()
. The first copies "de" just as you described.
The second one copies "vwxyz" to the address of the third character in s
(s + 2
). Since s
is just two characters long, it effectively appends "vwxyz" to "de".
Upvotes: 3
Reputation: 1761
You find s+2 the same way you found a+3. In this case, the third character of s is the \0 that got copied over the first time (and is replaced by this strcpy).
Upvotes: 0