char and char* (pointer)

Iburidu picture Iburidu · Oct 13, 2012 · Viewed 71.8k times · Source

I would like to understand how pointers work, so i created this small program. first of all i create a p pointer, which points to a char.

The first question is at this point. If i create a pointer, the value of it is a memoryaddress (if i point it to a non-pointer object), but this time it is "haha" in my example. Why does it work this way in char*? And how i can add value to it with cin >> p?

My second question is that, i created a q char, which has the value of the *p pointer at the point i created it. BUT its value and address are "h" too, but why? It must be the memory address of this char object! It's pointless :D (mingw - gcc)

#include <iostream>

int main() 
{
 /* char *p;
    cin >> p;                      //forexample: haha */

    char * p = "haha";
    char q = *p;
    std::cout << "&q = " << &q << std::endl;   //&q = h
    std::cout << "q  = " <<  q << std::endl;   //q = h

    return 0;
}

MORE: If i allocate memory first with char a[100]; char *p=a; then &q = h»ŢĹ, so "h" and some mess. but it should be a memoryaddress! and my question is, why is not it address then?

Answer

PiotrNycz picture PiotrNycz · Oct 13, 2012

Think of char* p; as of address in memory. You did not initialize this pointer so it does not point to anything, you cannot use it.

To be safe always:
either initialize pointer to zero:

char *p = 0; // nullptr in C++11

or initialize to some automatic

void foo() {
  char a[100];
  char *p = a;
}

or global memory:

char a[100];
void foo() {
  char *p = a;
}

or get dynamic memory:

char* p = new char [100];

Then you can use p (if not NULL) to read data and to read from p...


For your misunderstaning of operator >> (std::istream&, char* p). This operator expects that p points to some memory (automatic,global,dynamic - no matter) - it does not allocate memory by itself. It just reads characters from input stream until whitespace and copy it to the memory pointed by p - but p must already points to some memory.


For taking address of char q;. Of course you can take address of q: &q, and it type is char* p. But &q is different that p, and this q=*p just copies first character pointed by p to q, it cannot change address of q - its address is unchangeable. For cout << &q - operator << (ostream&, char* p) expects that p points to NULL terminated string - and &q points to memory containing "H" but what is after this character no one knows - so you will get some garbage on screen. Use cout << q to print single character.