简体   繁体   中英

How can char * name = “Duncan”; be valid if pointers can only hold addresses?

I thought that pointers can only hold addresses to other variables. So how can the following statement that I came across be valid? It's holding a string.

char * name = "Duncan"

Thanks.

It's holding a pointer to a string. That's not the same. name just contains an address of memory which contains the string.

"Duncan" is a null terminated string and as such an array of char ( {'D', 'u', 'n', 'c', 'a', 'n', '\\0'} ). char*name="Duncan"; sets name to the address of the array.

Your statement is OK in C, but in C++ "Duncan" is a const char array, so you should use const char *name = "Duncan" .

BTW, if you do not need to change the pointer variable name, it's better to have const char name[] = "Duncan" . This only allocates memory for the string. Your sample code allocates memory for the string and for the pointer variable name. (Of course the compiler might optimize away name.)

It's still pointing to a string. The string gets put in memory first, and name points to that. It's compiled into your program, so it may not be obvious.

pointers can only hold addresses to other variables.

This is incorrect: references hold addresses of other variables; pointers can hold addresses of anything, or even nothing in particular (eg NULL ).

In this case, name holds an address of a memory block of 7 bytes, containing ASCII codes for D , u , n , c , a , n , and \\0 .

In this particular case, the compiler will store the array with data Duncan\\0 somewhere in the object file and the pointer will point there.

So yes, the pointer is only holding an address. The data are somewhere else.

This brings me to saying, writing code like this is not so good. For example, if you change that string through your pointer, you get an undefined behavior.

That's a definition of a char pointer. After the definition, on the right side of "=", you have a constant definition. The constant is stored somewhere in memory and its address is used as first value for "name". Later on you will be able to assign other value to "name". You are not bound to the first value, in fact "name" is a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM