I need to find an alternative to c_str() function in C...
As stated in the comments above, C does not have a string type, but C does use arrays of char
, and when NULL terminated are commonly referred to as C strings.
There are many various methods to create strings in C. Here are three very common ways:
Given the following: (for illustration in this example)
#define MAX_AVAIL_LEN sizeof("this is a C string") //sets MAX_AVAIL_LEN == 19
1
char str[]="this is a C string";//will create the variable str,
//populate it with the string literal,
//and append with NULL.
//in this case str has space for 19 char,
//'this is a C string' plus a NULL
2
char str[MAX_AVAIL_LEN]={0};//same as above, will hold
//only MAX_AVAIL_LEN - 1 chars for string
//leaving the last space for the NULL (19 total).
//first position is initialized with NULL
3
char *str=0;
str = malloc(MAX_AVAIL_LEN +1);//Creates variable str,
//allocates memory sufficient for max available
//length for intended use +1 additional
//byte to contain NULL (20 total this time)
Note, in this 3rd example, Although it does not hurt,
the "+1" is not really necessary if the maximum length of
string to be used is <= the length of "this is a C string".
This is because when sizeof() was used in creating MAX_AVAIL_LEN,
it included the NULL character in its evaluation of the string
literal length. (i.e. 19)
Nonetheless, it is common to write it this way when allocating memory for C strings
to show explicitly that space for the NULL character has been considered during memory allocation.
Note 2, also for 3rd example, must use free(str);
when finished using str
.
Look here for more on C strings.