Q:

Different content of a

Im looking for a better understanding of the following 3 examples. 
This is my questions to the following code examples.

Ex. 1. Example makes sense, it outputs the adress of which the int a
is stored. 
Ex. 2. Makes a little less sense for. I think it is
because the char itself points to the char?  
Ex. 3. Confuses me. In
the output the first char output is always the on stored in the char.
But what are the appending chars and why do they appear after saving
&a to a char pointer?

Lastly how do i output the adress of the memory location of where a char variable is saved?
Ex. 1
main(void) 
{
  int a = 1;
  cout << &a;
}

Outputs the memory adress ex. 0x7fff4241b7b4
Ex 2.
main(void) 
{
  char a = 'a';
  cout << &a;
}

Outputs the char a. ex. a
Ex. 3.
main(void) 
{
  char a = 'a';
  char *b = &a;
  cout << &a;
}

Outputs a��:��

A:

The first pointer matches the operator<<(const void*) that outputs the pointer value; the second and third match operator<<(const char*) that will output a null-terminated string.
char a is a value on stack, so it is totally undefined whether the bytes after the first byte are null or not, luckily in the middle case it is followed by a null byte, but in the 3rd case some bytes following are not null bytes and you get broken UTF-8 characters. The fact that you are setting a pointer does not affect the running of the program, but the stack frame is set up differently, and GCC for example emits movb    $97, -9(%rbp) assembler opcode to set the byte on stack, putting the char in a non-aligned address. The stack layout on my computer is this (64 bit)
| x | x | x | x | x | x | a | b | b | b | b | b | b | b | b |
                                                            ^
                                                           RPB

Thus a is then on stack directly followed by the b pointer value; the garbage I see when running on my machine comes from this pointer value. In fact if I change the ex 3 into 
#include <iostream>

int main(void) 
{
    char a = 'a';
    long b = 0x68676665646362l;
    std::cout << &a;
}

I get output
abcdefgh

Of course this is an example of undefined behaviour; compile using another compiler, run on another platform and the program can according to standards as well crash, print the complete text of Hamlet or achieve self-awareness.

