why does array of char in c++ have values that i didn't assigned them?
For ex:
char arr[5]={'a','b','a','s','s'};
int i=0;
while(arr[i])
{ cout<
Where did i get these from ", i ? And , how do i eliminate this error( by using the same algorithm to print)?
good programming practice int i=0 should come first before char ... another thing is that ur condition must be assigned something in order the repeatation to take place . try this int i=0; char arr[5]={'a','b','a','s','s'}; while(i < 5) { cout<<arr[i]<<endl; i++; }
When you compile a program, an executable file is created. Somewhere inside that file, the characters 'a','b','a','s' and 's' will be stored. The variable `arr` knows where the first 'a' is stored and from there it can be used to access the other characters. What `arr` does not know is how long the array is. In your loop, eventually `i` will become 5, then 6 and so on. If you ask for `arr[5]` (arrays start with index 0, so arr[4] will be the last element in your array), you will get the character that follows the 's' in your executable file. This can be another array or something else entirely.
Sorry for the two replies, but what walters said about a condition would fix your program. Since the variable `arr` does not know the length of the array, you, the programmer, must make sure that `arr[5]` is not accessed. This can be done by checking if `i < 5`. You can also keep your original while loop (which stops as soon as a zero value is found) and change the array a bit. Strings in C and some strings in C++ (the ones that do not use std::string) are ended by setting the last character to 0 or '\0' (which are the same). So if you define your array as `char arr[6] = {'a','b','a','s','s','\0'};`, your code will also work. On a side note, this is precisely what happens when you define a string in C: `char *arr = "abass";` will give you the same array as the one I mentioned.
Thank You Guys. I really appreciate it.
An array of char is NOT the same as a string, although a string is stored as an array of char. string has a 0 byte terminating the ( logical ) string. An array of character just holds n char, unless you assign it, it doesn't have a terminating char. Your code was basically a buffer overrun. You originally kept outputting characters until you found a terminating ( \0 ) character. Since your array didn't have a terminating char, the loop continued, overrunning the end of your array and outputting whatever was next in memory. You're kind of lucky that it only went 3 chars before it got a \0.
Join our real-time social learning platform and learn together with your friends!