1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Strings and Pointers, I'm confused!

Discussion in 'C' started by tedman, Feb 8, 2007.

  1. tedman

    tedman New 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?
     
  2. shabbir

    shabbir Administrator Staff Member

    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)){
     
  3. tedman

    tedman New Member

    thanks boss! problem solved!
     
  4. DaWei

    DaWei New Member

    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';
    
     
  5. tedman

    tedman New 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?
     
  6. tedman

    tedman New 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
     
  7. DaWei

    DaWei New Member

    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: Feb 8, 2007
  8. shabbir

    shabbir Administrator Staff Member

    X is incremented after being assigned. i.e. 30++
     

Share This Page