Well as the title says, I have an array of strings (delimited by null). The length of the array is variable and length of each string is variable as well. What I need is one huge string with the original strings in the array separated by spaces.
For example is an array is such that array[0] = Firstname, array[1] = Secondname, I want to be able to extract that and store it in a char * which would then be "firstname Secondname".
So I figured out how to do it. In case, anybody else are looking for the same thing, I am posting my version here:
/*
* Subroutine to extract the full name by concatenating
* array of strings into one full string separated by spaces.
*
* Input: number of fields and array of strings
* Returns: full string name (char *)
*/
char *get_full_name(int n, char **f){
int tot_length = 1, i;
char *p, *result;
const char *current;
for (i = 1; i < n; i++){
tot_length += strlen(f) + 1;
}
result = (char *) malloc ((unsigned) tot_length);
for (p = result, i = 1; i < n; i++){
current = f;
if (strlen(current) == 0){
continue;
}
memcpy(p, current, (size_t) strlen(current));
p += strlen(current);
*p = ' ';
p++;
}
return (result);
}
I am not sure whether it is the perfect way to do it..but it works :).
I can see a couple of problems already. You are assuming arrays in C index from 1 instead of 0. You are adding a trailing space to your result string. You are not adding a '\0' to the end of your result string.
Thanks for your comments. The index problem is actually not a problem because this function is part of a program I am writing and I know that whatever I need will start from index 1 (because I am passing it that way). That can be changed here.
Could I just add a null at the end of result like say:
Don't know why it would crash on Linux (works fine on AIX) and you say it's strlen that's causing the crash. To get a stack trace do the following and post the output...
No core file? that's strange. What compiler and version you got? Maybe the compiler on Linux doesn't like that f is set to NULL so give the code below a try...