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 😀 (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?
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:
or initialize to some automatic
or global memory:
or get dynamic memory:
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 thatppoints 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 byp– butpmust already points to some memory.For taking address of
char q;. Of course you can take address ofq:&q, and it type ischar* p. But&qis different thatp, and thisq=*pjust copies first character pointed byptoq, it cannot change address ofq– its address is unchangeable. Forcout << &q–operator << (ostream&, char* p)expects thatppoints to NULL terminated string – and&qpoints to memory containing"H"but what is after this character no one knows – so you will get some garbage on screen. Usecout << qto print single character.