PDA

View Full Version : string to char*?



nass
2nd January 2007, 16:13
hello everyone,
this is a rather newbie question, but strings confuse me way too often.

i have a readFromTextFile() function
in which i read in a string array lines of text. string lines[6].
now i want to save each string to a char * variable.
i guess i will have to do malloc for each char* variable but then?
should i memcpy? strcpy? or am i completely of course here?
what should i do?
thank you for your help.
nass

jacek
2nd January 2007, 16:32
i guess i will have to do malloc for each char* variable but then?
should i memcpy? strcpy?
memcpy() and strcpy() are almost the same, but since you are dealing with strings, you should use strcpy() or strncpy().

There are also strdup() and strndup() which work like malloc()+strcpy().

nass
2nd January 2007, 16:39
thank you for the quick reply.
but is it 'legal' in c++ terms to cast

(char*)&lines[1], in order to use it as source pointer in strcpy?

jacek
2nd January 2007, 16:47
but is it 'legal' in c++ terms to cast

(char*)&lines[1], in order to use it as source pointer in strcpy?
No, you have to use string::c_str() to get a const char *.

http://www.cppreference.com/cppstring/c_str.html