Archived

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

how to convert char[] to char*

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

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 on other sites
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 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 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];

malloc()

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 on other sites
quote:
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.

1. 1
Rutin
32
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 14
• Forum Statistics

• Total Topics
633326
• Total Posts
3011373
• Who's Online (See full list)

There are no registered users currently online

×