Distinction between character pointers and character strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Distinction between character pointers and character strings

I am confused as to why for example: Char* szmyName = "farouk"; can take a string as its value but char* psztoName = szmyName; takes up the address of the first element? what's the distinction and how does C++ interpret them?

28th Nov 2016, 11:49 AM
Gbadamosi Farouk
Gbadamosi Farouk - avatar
4 Answers
+ 4
The difference lies in the handling of arrays. Arrays are directly pointers and you "dereference" them with the address of the specific place of the first element. Since strings are character arrays you automatically get a pointer for the object pointing to the first character of that string. Think of it as simple values have to be referenced by the address-of operator whilst arrays give you the address directly.
28th Nov 2016, 3:21 PM
Kerem Adıgüzel
Kerem Adıgüzel - avatar
+ 1
Thank you kareem. If I am clear on what you are saying is that strings are character arrays and derefencing them points to the first character in the array. This brings me to my second question as to why 'char* whatever ' can take a string as its value? since its a pointer it should only take an address as in 'int* p = &someVar'?
28th Nov 2016, 4:41 PM
Gbadamosi Farouk
Gbadamosi Farouk - avatar
+ 1
As I said strings are actually character arrays. They are just written differently because they are used widely. Consider the awkwardness of having to define "Hello world" explicitly as a character array: {'H', 'e', 'l', 'l', .... }. It is just a very convenient syntactical shortcut to define an array of characters. That's why you can use strings for character pointers directly.
28th Nov 2016, 4:46 PM
Kerem Adıgüzel
Kerem Adıgüzel - avatar
+ 1
Thank you very much
28th Nov 2016, 5:20 PM
Gbadamosi Farouk
Gbadamosi Farouk - avatar