Reputation: 1531
Do you have to manually loop through the array once and get a count of the strlen of each character array, sum it, allocate destination with the summed value and then loop over the array again?
How do you find the size of the array that contains the arrays of characters so you can iterate over them?
Upvotes: 5
Views: 22029
Reputation: 44240
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *nstrdup(char **args);
int main (int argc, char **argv)
{
char * this;
this = nstrdup(argv+1);
printf("[%s]\n", this );
return 0;
}
char *nstrdup(char **args)
{
size_t len, pos;
char **pp, *result;
len = 0;
for (pp = args; *pp; pp++) {
len += strlen (*pp);
}
result = malloc (1+len);
pos = 0;
for (pp = args; *pp; pp++) {
len = strlen (*pp);
memcpy(result+pos, *pp, len);
pos += len;
}
result[pos] = 0;
return result;
}
Upvotes: 0
Reputation: 363517
How do you find the size of the array that contains the arrays of characters so you can iterate over them?
There are two ways:
char*
at the end of the array and store a null pointer in it as a sentinel, similar to the way a NUL character is used to terminate a string.In other words, you have to do your own bookkeeping when allocating the array because C won't give you the desired information. If you follow the second suggestion, you can get the total number of characters in the array of strings with
size_t sum_of_lengths(char const **a)
{
size_t i, total;
for (i = total = 0; a[i] != NULL; i++)
total += strlen(a[i]);
return total;
}
Don't forget to reserve space for a '\0'
when doing the actual concatenation.
Upvotes: 7
Reputation: 5456
I guess that you want to concatenate the strings. If so, yes. You have to know how much space you want before you allocate it.
In fact, you can use realloc
, but it's really just copy the previous string every time, and much less effective.
Some code : (assuming char *s[]
and int n
)
int i,l=1;
for (i=0;i<n;i++) l+=strlen(s[i]);
char *r=malloc(l);
r[0]=0;
for (i=0;i<n;i++) strcat(r,s[i]);
Edit: As some comments, strcat
is ineffective when you know the length. (I still prefer it since it allocate the memory in one time.) Some more effective code is:
int i,l=1;
for (i=0;i<n;i++) l+=strlen(s[i]);
char *r=malloc(l);
char *d=r;
for (i=0;i<n;i++) {
srtcpy(d,s[i]);
d+=strlen(s[i]);
}
Upvotes: 0
Reputation:
I assume you are trying to make a string that is the concatenation of all of the strings in the array.
There are 2 ways of doing this:
Make 2 passes as you suggest, summing the lengths in the first pass, allocating the destination string, and then appending the strings in the second pass
Make 1 pass. Start by allocating the buffer to some size. Append the strings, keeping track of the total size. If you don't have enough room for a string, reallocate the buffer with realloc()
. The most efficient method of reallocation will be to double the size of the buffer each time.
Upvotes: 1