Strings and Pointers, I'm confused!

tedman's Avatar, Join Date: Jan 2007
Go4Expert Member
Code:
main() {

char *s1 = "Hello, World!";
char *s2;
s2 = (char *)malloc(strlen(s1)*sizeof(char));


int i=0;

while(i<strlen(s1)){
s2[i]=s1[i];
i++;
}

i=0;
while(i<strlen(s2)){
printf("%c", s2[i]);
i++;
}

printf("\n%d", strlen(s1));
printf("\n%d", strlen(s2));

}
The above program is an implementation of strcpy()
now for this example the length of s2 is greater than s1, shudnt it be the same??
the answer i get is "Hello, World!o"
length of s1 = 13
length of s2 = 14
why is this happening?
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Just copy the \0 also from the first string or just add one at the end and then you will get the buffer calculated by strlen correct.

strlen returns the no where it finds \0

Try changing
while(i<strlen(s1)){
to
while(i<=strlen(s1)){
0
tedman's Avatar, Join Date: Jan 2007
Go4Expert Member
thanks boss! problem solved!
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You might find this more efficient, as there's no need to invoke the strlen function each time:
Code:
	while (*s1)  *s2++ = *s1++;
	*s2 = '\0';
0
tedman's Avatar, Join Date: Jan 2007
Go4Expert Member
I usually get confused with the ++ operator, please can u try to clarify it.
Code:
supposed x = 10, y = 20
z = x++ + y++;         z=30

now if it is
x = x++ + y++       x=31
how does this happen?
0
tedman's Avatar, Join Date: Jan 2007
Go4Expert Member
I guess I'll answer my own question! correct me if im wrong.
in the first case z = 10 + 20

in the second case
1. x = 10+20 = 30
2. x and y get incremented after 1. that is y is 21 and x is its value plus one, that is its current value 30+1 = 31
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
The post-increment operator increments the operand AFTER it is evaluated. It's as simple as that.

You have to be careful using these operators multiple times on one operand in one expression. Such usage can result in undefined operation, wherein your compiler can do anything it likes. Read about sequence points.

Incidentally, your original example is not an example of a "strcpy", it's an example of a "strdup", which gets memory from the heap and makes a copy using it.

Last edited by DaWei; 9Feb2007 at 03:42..
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
X is incremented after being assigned. i.e. 30++