• Advertisement

Archived

This topic is now archived and is closed to further replies.

how to convert char[] to char*

This topic is 5001 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hello simple question how would you convert a array of char[] into a char* i know it can be done with a function but carnt remeber what it is called thanks rolf

Share this post


Link to post
Share on other sites
Advertisement
You mean

char mytext[100];
char *pointer_tochars = &mytext; ?

EDIT:

Or if you don't want the mytext to go out of scope... char *mytext = new char[100];

Then you don't need the conversion... (but you need to remember to delete [] mytext)

[edited by - downgraded on June 9, 2004 3:36:59 PM]

Share this post


Link to post
Share on other sites
Technically an array name is synonymous with a pointer to the first element of an array. So:

char foo[100];
char *fooptr = foo;

char *fooptr = &foo; will throw an error because that resolves to char **.

I'm assuming the question is what you put in the subject, not that you want a char* pointer to the first element of an array of arrays.

-fel

[edited by - felisandria on June 9, 2004 3:39:40 PM]

Share this post


Link to post
Share on other sites
An array is actually a pointer to the start of the array. That means that you can just do this:

char array1[8];
char *arraypointer = array1;

And you can access the array the same way:

arraypointer[3];

Share this post


Link to post
Share on other sites
the function is dynamic it is an alterneative to malloc() but it uses it inside its self.

i remember what it was now

so ill tell you


strdup()

its allso good to free the returned variable after its use due to the strdup using malloc inside.

thanks

rolf

[edited by - maddnig on June 9, 2004 4:07:04 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by maddnig
the function is dynamic it is an alterneative to malloc()

i remember what it was now

so ill tell you


strdup()


thanks

rolf


Not exactly, it just duplicates strings, nothing to do converting an array to a pointer, you can''t return arrays only pointers/references to an instance be it a sole instance or an element of some array and as a name of an array can be treated as constant pointer to the first element thats why it''s returning a pointer.

Share this post


Link to post
Share on other sites

  • Advertisement