Home > Back-end >  Can someone explain why to[i] = '\0' is correct?
Can someone explain why to[i] = '\0' is correct?

Time:08-17

It's a function that should copy a given string into another string. Can someone explain me why to[i] = '\0' is correct without to i after the loop has stop and what means before and after i.

 #include <stdio.h>

void copyStringArr(char to[], char from[]);

int main(void)
{
    char string1[] = "A string to be copied";
    char string2[250];

    copyStringArr(string2, string1);
    printf("%s\n", string2);
    
    return 0;
}

void copyStringArr(char to[], char from[])
{
    int i;
    for(i = 0; from[i] != '\0'; i  )
        to[i] = from[i];
    to[i] = '\0';
}

CodePudding user response:

Let's copy a 2-char string ("hi") instruction by instruction ..

// from = "hi"
// to = "HERE BE DRAGONS..." // garbage

i = 0;
from[0] != 0     // is true
to[0] = from[0]; // to = "hERE BE DRAGONS..."
i                // i is 1 now
from[1] != 0     // is true
to[1] = from[1]; // to = "hiRE BE DRAGONS..."
i                // i is 2 now
from[2] != 0     // is false, so exit loop
to[2] = 0;       // terminate string, don't care about i anymore
                 // to = "hi"; the DRAGONS (the initial garbage) are
                 // still in memory, you need "special tricks" to see them

CodePudding user response:

Because for loops are executed as:

  • Execute once: i = 0;.
  • Then loop:
    • Check from[i] != '\0'
    • Execute loop body.
    • Execute i .

The last full lap of the loop executes i and then the next from[i] != '\0' check yields true. That's where it stops and i was already incremented so that its value corresponds to the index of the null terminator.


You can illustrate it with this code that uses the comma operator to sneak in a printf at each of the mentioned steps:

for(int i=(printf("[i=0]\n"),0); 
    printf("[i<3] "), i<3; 
    printf("[i  ]\n"), i  )
{
  printf("[loop body i: %d] ", i);
}

Output:

[i=0]
[i<3] [loop body i: 0] [i  ]
[i<3] [loop body i: 1] [i  ]
[i<3] [loop body i: 2] [i  ]
[i<3] 
  • Related