Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Char Pointer in c++

Status
Not open for further replies.

n0nick

Programmer
Apr 28, 2005
32
0
0
NO
I have some questions about char-pointers in c++. I have made a image <img src="

of what i THINK is happening when i write
char c[] = "hello";
char* c2= c;

and
char c = "hello";
char* c2= c;


Is this image correct? How can adress of "c" be the same as c[0] and c in the first image?

And why is "c2" pointing to "c[0]" and not to "c" in the last image?
 
In your first example, c is a character array, not a pointer, and the address of c is the same as c[0]. In your second example (overlooking the typo missing the * in declaring c), c is declared as a pointer to a character array that is stored elsewhere in memory. This is how char * differs from char [], though C/C++ usually makes the difference invisible to the programmer.

You'll find if you have a function that returns a char *, and you try to return a char [], you'll get a compiler error until you change the code to

return &arrname [0];

which is the memory address of the first character in the array, and is a valid char *.

Lee
 
void __fastcall TForm1::Edit1Click(TObject *Sender)
{
char c[] = "hello";
char* c2= c;

ShowMessage(c2);
}

In this example I droped the TEdit control on a form and used
the event OnClick. And the char pointer worked fine.

How can adress of "c" be the same as c[0] and c in the first image?

ShowMessage(c[0]); will return h. you are accessing only the first char of the area.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top