×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Char Pointer in c++

Char Pointer in c++

Char Pointer in c++

(OP)
I have some questions about char-pointers in c++. I have made a image <img src="http://www.slomic.no/char_pointers.gif">


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?

RE: Char Pointer in c++

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

RE: Char Pointer in c++

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.

 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close