Confusion About Char Array Pointer Assignment

Hello everyone! I understand the premise of pointers, but I'm confused about the following code:

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

const int MAXCHAR = 101;
int main()
{
	char msg[MAXCHAR];
	char *strptr;

	strcpy_s(msg, MAXCHAR, "This is a good example!");
	strptr = msg;
	//output through strptr
	cout << strptr << endl;
	cout << msg << endl;

   return 0;
}


Both outputs give me "This is a good example!" But what confuses me is when I work with int pointers, you have to assign it first with the address of operator, and to print the actual value you print it with the dereferencing operator.

But here, we just assign msg to strptr and can print strptr with no dereferencing operator, and it doesn't seem to have anything to do with the memory location of msg.

Can anyone set my logic straight? It'd be much appreciated, I don't know why this is confusing me so much.

Thank you!
Last edited on
I think your question is why cout << strptr prints the text in msg. C uses an array of character as string, and C++'s cout treats char* as a string (C string be precise).

line 10 copies the text into msg, i think you're pretty sure about that.
line 11 assigns the msg to a char*. There's no allocation involved. In C we can use a pointer to point to an array.

To make it easier to understand, you can print a string with

cout << "This is a good example";

And the type of "This is a good example" is char*.

I see! Thank you liuyang. Now that I think about it, the only time the address of operator and dereferencing operator seem to be used is with int pointer variables. C-strings and dynamic memory allocation seem to only require declaring the variable as a pointer variable, and then you essentially treat it as a regular variable.

If dynamic, you must delete after declaring a new variable.
Topic archived. No new replies allowed.