Please help array problem? -Beginner

Why does this give me this result? http://i.imgur.com/SUm6TN7.png
(Learning about pointers etc. and how they relate with arrays)
IDE: Visual Studio 2013
When I put this char anArray[] = {'9', '7', '5', '3', '1' };
I still get the numbers cout, but still get the weird characters as shown above... Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main(){
	int dank = 1;
	char anArray[] = {9, 7, 5, 3, 1 };
	
	std::cout << anArray;
	


		

	while (dank == 1) {};
}
Because you put integers into an array of chars, they automatically cast to chars. But, except the tab, none of those are printable characters: http://www.asciitable.com/

EDIT: What do you mean you "still get the numbers cout"? Also, the weird characters are left over garbage from memory because you don't have a null terminator in your c-string.
Last edited on
If these aren't printable characters why do they print okay when I put this:
char anArray[] = {'9', '7', '5', '3', '1', '\0'};
std::cout << anArray;

Thanks for the help, I had a suspission it was something to do with me not terminating the string but I thought it did that automatically...
When you include the single quotes around the value they are seen as chars, without them they are seen as integers.
Ohhhh Okay but, if I put
char anArray[] = {9, 7, 5, 3, 1, '\0'};
I still get random ascii characters, why?
(If they are in my memory why are they there in the first place, why those characters?)
Last edited on
char anArray[] = {9, 7, 5, 3, 1 };

if you want an array that stores single bytes only, in order to save space you can use following:

1
2
3
4
5
typedef unsigned char byte;
byte anArray[] = {9, 7, 5, 3, 1 };

int x = anArray[3];
std::cout << x;
Last edited on
OP wrote:
If they are in my memory why are they there in the first place, why those characters?

You my friend seem to underestimate how lazy your computer really is. Memory that is de-allocated when a program closes or when a variable is releases\falls out of scope is not necessarily zeroed out. Also, when new memory is allocated to a process it does not have to be initialized to any value if the constructor of the variable does not explicitly tell it to so often times your computer will simply leave it as is.
Topic archived. No new replies allowed.