char * ??????

Mar 23, 2008 at 4:16pm
Hi all.
I am trying to get my head around pointers.
I created a little program::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main ()
{
	char a[20] = "this is a test";
	char * pa;
	pa = &a[0];
	for (int i =0; i< 20; i++)
	{
		cout << "Address: " << pa << ", value: " << *pa << endl;
		pa += 1;		
	}
  return 0;
}


The ouput from which is:
Address: this is a test, value: t
Address: his is a test, value: h
Address: is is a test, value: i
Address: s is a test, value: s
Address: is a test, value:
Address: is a test, value: i
Address: s a test, value: s
Address: a test, value:
Address: a test, value: a
Address: test, value:
Address: test, value: t
Address: est, value: e
Address: st, value: s
Address: t, value: t
Address: , value:

I can understand the value, but shouldn't the address be a hex address in memory? when i run the same with a int * i do get a hex memory address increasing by 4, since for my compiler sizeof(int) = 4. Please could someone explain?

Many thanks all,
Matthew
Mar 23, 2008 at 5:09pm
hello matthew
if you pass a char * to cout, you'll get the string it points to until the \0. try this
cout << (void*)pa;
mfg goti
Mar 23, 2008 at 7:57pm
Like goti said, but in further detail, char* in C++ is interpreted as C-style string. When you print out a char* to iostream, functions are called in <cstring> library that prints char* as a string that terminates with '\0'.

So a pointer to a void is your option.
Mar 23, 2008 at 9:18pm
Hi all,
Many thanks for your response. It now works!
However I am still a bit confused as to why the (void*)pa works. Are we casting the char* type to a void* type? I didn't think that we could do this?

Again, many thanks,
Matt
Mar 23, 2008 at 9:44pm
Yes, you can cast any pointer to void*. You can also assign any pointer to a variable of type void*. A void pointer is like a variable containing a memory address, without any information about what is contained in the memory address. However, converting from a void pointer to a pointer of a specific type is more restricted (and more dangerous).

I would suggest to use a C++ style cast, instead of the C style:
1
2
3
4
// C style:
cout << (void*)pa;
// C++ style:
cout << static_cast<void*>(pa);

C++ style casts are more restricted and somewhat safer to use. They also stand out better in your code, and reminds you that casting is often a bad thing that you should try to avoid.

In this case, it is also possible to avoid the cast like this:
1
2
void *ptr = pa;
cout << ptr;

Topic archived. No new replies allowed.