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 );
Comments
-
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 about 10 yearsYour while loop does not copy over the
\0
character to finalize yourtemp
string. It finishes prematurely. You could change it into a do-while-loop. You also do not need two counter variablesi
andj
since they both have the same value. -
Ahmed about 10 yearsYou haven't understood my question!
-
tiguchi about 10 yearsWell, you obviously do not understand my comment.
-
Ahmed about 10 yearsI do but what you are saying isn't what I've asked
-