Null terminator at the end of char array in C++

13,359

The difference is in the way of the definition of temp.

In the first case

char temp[50] = "anything";

temp is initialized. All its elements that was not assigned a character from the string literal were zero initialized.

In the second case

char temp[50];

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

There is a third case when temp had static storage duration. In this case if it is defined as

char temp[50];

all its elements are initialized by zero.

For example

#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;
} 

Also take into account that it would be more safe and effective to use standard C function strcpy to copy source into temp. For example

#include <cstring>

//...

std::strcpy( temp, source );
Share:
13,359
Ahmed
Author by

Ahmed

Computer vision and deep learning enthusiast.

Updated on June 04, 2022

Comments

  • Ahmed
    Ahmed almost 2 years

    Why it isn't necessary to store null character at the end of the string 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 case below 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
    
    • tiguchi
      tiguchi about 10 years
      Your while loop does not copy over the \0 character to finalize your temp string. It finishes prematurely. You could change it into a do-while-loop. You also do not need two counter variables i and j since they both have the same value.
    • Ahmed
      Ahmed about 10 years
      You haven't understood my question!
    • tiguchi
      tiguchi about 10 years
      Well, you obviously do not understand my comment.
    • Ahmed
      Ahmed about 10 years
      I do but what you are saying isn't what I've asked