Reputation: 2266
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
Upvotes: 3
Views: 16548
Reputation: 92
To add something.. in the definition of temp[] in the first sample you use the following code:
char source[50] = "hello world";
char temp[50] = "anything";
int i = 0;
int j = 0;
You see, the length of source (strlen) is 12, the length of temp is 9.. you also initialized the variable i and j to zero..
The location of i and j variables in the memory are actually right after the temp array.. So, for temp array, at location 12 (at the length of source array) this location has been already initialized to 0 by the definition and declaration of i and j variables. So, you don't need the temp[j] = '\0' anymore..
Upvotes: 0
Reputation: 310930
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 );
Upvotes: 9