Search code examples
carraysstringnullcopying

Copying elements from one character array to another


I wanted to transfer elements from a string to another string, and hence wrote the following program. Initially, I thought that the for loop should execute till the NULL character (including it i.e) has been copied. But in this code, the for loop terminates if a NULL character has been found (i.e, not yet copied), but its still able to display the string in which the elements have been copied. How is this possible, if there is no NULL character in the first place?

#include<stdio.h>
#include<stdlib.h>

int main()
{
    char temp[100], str[100];
    fgets(str, 100, stdin);
    int i;
    for(i = 0; str[i]!='\0'; i++)
    {
        temp[i] = str[i];
    }
    puts(temp);
    return 0;
}

Solution

  • The void puts(const char *) function relies on size_t strlen(const char *) and output of this function is undefined when there is no null terminator in the passed argument (see this answer). So in your case the strlen inside puts probably found a 0 value 'next to' your array in memory resulting in a proper behavior of puts, however that need not always be the case as it's undefined.