I have the following doubt:
If i declare a pointer to a character, and assign it an address of a memory location with 'a' in it, and the 'cout' this pointer, according to my logic, the 'cout' function should start printing from 'a' till it receives first blank character.
e.g.
char * c = new char('a');
cout << c;
but the output is only 'a'. How come every time the next byte is a blank character? or is there a flaw in my understanding?
if i do following:
char *c = new char('a');
c[1] = 'r';
cout << c;
then the output is 'ar'.
This makes it a bit more confusing...
char *a = newchar('a'); // allocated only space for 1 character
char *b = "b"; // b points to an array that consists of the character 'b' and a null terminator.
where you alter the character after 'a' is undefined behavior.
cout will print until it finds a null character '\0'. The OS often sets all memory to 0 before giving it to the process so it is not strange if c[1] is always null for your program.
c[1] = 'r'; This is not safe. The memory you write to could be part of some other data so it could cause bugs in other parts of your program or even crash your program.
If you want to print the character that c points to you should dereference the pointer first. cout << *c;
Thank you Peter. But, isn't there garbage value in the memory? I din't know that the OS sets all the memory to 0 before giving it to the processes. Is the garbage because some process used that memory, and then left it?
(Like i said, it was a conceptual doubt, and i understand that c[1] is not correct.)
Thank you Peter. But, isn't there garbage value in the memory?
Garbage is garbage. It means it could be anything. It might be zero, it might not be.
I din't know that the OS sets all the memory to 0 before giving it to the processes.
It doesn't. That would be tremendously wasteful.
Some compilers, however, for debug builds, do in fact wipe all process memory to 0 or some other easily recognizable number (0xDEADBEEF) so that you can see when you're using uninitialized/bad memory.