Link to home
Start Free TrialLog in
Avatar of kishan66
kishan66Flag for United States of America

asked on

convert Char * to char array in C

Hi,

i have a function which takes char * as parameter
example :- getname("jack")  // where uname has values from a caller
getname(char *uname)
{
   TCHAR  myName [] =(L) uname; // i know this is wrong.
                                                      // i want to typecast value in uname to "L" and copy in   myName.
}

please let me know how to do that exactly in the above scenario.

Environment  - C -win32
IDE -- VS2008
Avatar of Infinity08
Infinity08
Flag of Belgium image

If you want a local copy of the string, you can do something like this :
void getname(char *uname) {
  char *myName = (char*) calloc(strlen(uname) + 1, sizeof(char));
  strcpy(myName, uname);
 
  // use the string ...
 
  free(myName);
}
 
/* OR : */
 
void getname(char *uname) {
  char myName[256] = "";
  strncpy(myName, uname, 256);
  myName[255] = '\0';
 
  // use the string ...
}

Open in new window

Ignore the // commenting style - that's only valid in C++ and C99, not in C.


If it's something else you need, could you describe what you are trying to do ?
what is (L), and what do you want to do with  myName?  why can't myName be char *?
Avatar of kishan66

ASKER

the reason why i want  to typecast function parameter "uname" to L and finally get the values into    TCHAR []  is...
i have to pass the value to a function which takes -- LPCWSTR .
so i'm trying to convert "uname".  some thing like this...
-----------------------------------------------------
getname(char *uname)
{
   TCHAR  myName [] =(L) uname; // i know this is wrong.
                                                      // i want to typecast value in uname to "L" and copy in   myName.
}
-------------------------------------------------------
hope i made myself clear. else , let me know.

Hi,infinity
thanks for the reply ..
but as i mentioned above...i have to pass the retrieved value as a parameter of type LPCWSTR .

Thank you
Well, it depends whether TCHAR is a wide character or a normal character. For a normal character, the code I posted above is fine (you might not even have to copy the string, and use the original instead). For a wide character, you could use mbstowcs instead :

        http://www.cplusplus.com/reference/clibrary/cstdlib/mbstowcs/
ASKER CERTIFIED SOLUTION
Avatar of Subrat (C++ windows/Linux)
Subrat (C++ windows/Linux)
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial