hongky said:
#include <stdio.h>
#include <string.h>
char str[128];
char append[128];
sprintf(str, "%s%s", str, append);
is it standard use?
i test it in VC & GCC.
the result is different, so weird! who can tell me the reason.
There's a logical error.
str is of 128 and so is 'append'. When you append 'append' to 'str' it
will write to some memory locations beyond 'str' and corrupt them. The
overwriting can 0 to 128 locations, 0 when str is empty first element
is '\0' and 128 when last element is '\0'.
This is why the result is different.
No, that is *not* the reason the result is different. The reason it is
different is because it is copying between objects that overlap,
specifically it is copying str over itself. This is undefined behaviour
even if both str and append contain 2 character strings.
To see for your self:
******************************
char str[12]="some__string";
char append[12]="same__string";
Did you realise that neither of these arrays contain '\0' terminated
strings? You need 13 byte long arrays if you want to fit "some__string"
in to it.
char *next=str+(sizeof(char)*(sizeof(str)+sizeof(append)));
sizeof(char) is guaranteed to be 1, so all you are doing is making this
harder to read.
char *next=str+(sizeof(str)+sizeof(append));
However, this still invokes undefined behaviour since you are creating a
pointer that is more than 1 past the end of str.
To be honest, I can't even see what you were trying to demonstrate with
this code, it is so badly written.
More undefined behaviour, writing to a byte off the end of the array you
started the pointer from.
printf("before copy %c\n",*next);
sprintf(str, "%s%s", str, append);
This is even worse than the OPs code since str and append do not contain
strings since there was no null termination.
printf("after copy %c\n",*next);
******************************
I didn't chk the result on gcc.
Hope this helps.
I hope that no one thinks the code you posted helps since it was far
worse than what the OP posted. At least the OP only got one thing wrong.
I seriously suggest that you would be better off reading a good C text
book, such as K&R2, reading the FAQ for comp.lang.c (which I'm sure says
what K&R2 is) and asking questions about what you don't understand,
rather than posting incorrect advice.