Zero terminator at end of char array in C ++

Why there is no need to store a null character at the end of a line named temp in the following code

char source[50] = "hello world";
char temp[50] = "anything";
int i = 0;
int j = 0;

while (source[i] != '\0')
{
    temp[j] = source[i];
    i = i + 1;
    j = j + 1;
}
 cout << temp; // hello world

while in the following case it becomes necessary

char source[50] = "hello world";
char temp[50];
int i = 0;
int j = 0;
while (source[i] != '\0')
{
    temp[j] = source[i];
    i = i + 1;
    j = j + 1;
}
cout << temp; // will give garbage after hello world
              // in order to correct this we need to put temp[j] = '\0' after the loop
+3
source share
2 answers

The difference is in determining the definition of pace.

In the first case

char temp[50] = "anything";

temp is initialized. All its elements, which are not assigned a character from a string literal, were initialized to zero.

In the second case

char temp[50];

temp was not initialized, so its elements contain any arbitrary values.

There is a third case where temp has a static storage duration. In this case, if it is defined as

char temp[50];

all its elements are initialized to zero.

for instance

#include <iostream>

char temp[50];

int main()
{
    char source[50] = "hello world";
    int i = 0;
    int j = 0;
    while (source[i] != '\0')
    {
        temp[j] = source[i];
        i = i + 1;
        j = j + 1;
    }
    std::cout << temp;
} 

, C strcpy .

#include <cstring>

//...

std::strcpy( temp, source );
+9

-.. temp [] :

char source[50] = "hello world";
char temp[50] = "anything";
int i = 0;
int j = 0;

, (strlen) 12, 9.. j .

j temp. , temp 12 ( ) 0 j. , temp [j] = '\ 0.

0

All Articles