I want to convert my char array to a string so I can pass it into a function. Say if I have this:
char array[3] = {'1', 'a', '/'};
and I want to convert it to
char *string = "1a/";
Do I just add a NULL terminator on the end?
I want to convert my char array to a string so I can pass it into a function. Say if I have this:
char array[3] = {'1', 'a', '/'};
and I want to convert it to
char *string = "1a/";
Do I just add a NULL terminator on the end?
Just add a zero-delimiter
char array[4] = {'1', 'a', '/', '\0'};
Declare your array like this
char array[] = {'1', 'a', '/', '\0'};
or
char array[] = "1a/";
First of all, a char array and a char pointer are mostly the same, can at times be used interchangeably, but ultimately, a char[] has a known size, making it possible to use the sizeof() function, whereas char* just points to the first address of contiguous memory of unknown length, so sizeof will return whatever your default size for integers are (4 on 32-bit systems, 8 on 64-bit systems) to indicate the size required to store an address.
But generally the rule with strings are that they have to be null-terminated, so it doesn't matter if you use char[] or char*. See examples below.
char array[4] = {'1', 'a', '/', 0};
OR
char string[4];
memset(&string[0], 0x00, sizeof(string));
memcpy(&string[0], &array[0], 3);
OR
char* string;
string = malloc(sizeof(array)+1);
memset(&string[0], 0x00, sizeof(array)+1);
memcpy(&string[0], &array[0], sizeof(array));
and then passing the string as a char* is as simple as:
void foo (char* bar, int n)
{
// do something with bar
}
and call it as
foo(&string[0], strlen(string));
Important to note, strlen can only be used on null-terminated char* strings.
If you have any questions, feel free to ask.