Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Strings and Pointers, I'm confused! (http://www.go4expert.com/forums/strings-pointers-im-confused-t2915/)

tedman 8Feb2007 07:44

Strings and Pointers, I'm confused!
 
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?

shabbir 8Feb2007 09:18

Re: Strings and Pointers, I'm confused!
 
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)){

tedman 8Feb2007 09:37

Re: Strings and Pointers, I'm confused!
 
thanks boss! problem solved!

DaWei 8Feb2007 20:17

Re: Strings and Pointers, I'm confused!
 
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';


tedman 9Feb2007 01:40

Re: Strings and Pointers, I'm confused!
 
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?

tedman 9Feb2007 01:53

Re: Strings and Pointers, I'm confused!
 
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

DaWei 9Feb2007 03:40

Re: Strings and Pointers, I'm confused!
 
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.

shabbir 9Feb2007 11:31

Re: Strings and Pointers, I'm confused!
 
X is incremented after being assigned. i.e. 30++


All times are GMT +5.5. The time now is 20:34.