Here is a an array:
char *a[]={"I", "LOVE", "C", "PROGRAMMING"};
How to aggregate this array to a string in c?
That is,
char b[]="I LOVE C PROGRAMMING";
I had tried to use memcpy for each string, but I have no idea to add spaces in each other.
int width[4];
for(int i=0; i<4; i++)
width[i]=strlen(a[i]);
//aggregate the msg length
int agg_len[4];
int len_w = 0
for (no = 0; no < 4; no++) {
len_w += width[no];
agg_len[no] = len_w;
}
//compose msg
memcpy(b, a[0], width[0]);
for(idx = 1; idx < 4; idx++)
{
memcpy(b+agg_len[idx], a[idx], width[idx]);
}
and the result is "ILOVECPROGRAMMING"
How to fix it to "I LOVE C PROGRAMMING"
I have tried add spaces but failed with wrong memory address when I using memcpy
because it need add 1 length after each step (" " need 1 length)
"I","LOVE","C","PROGRAMMING"with spaces is the same as joining the strings"I"," ","LOVE"," ","C"," ","PROGRAMMING"without. Does this help? But I think you can simplify your approach: Just concatenate the strings as you go. There is no need to fiddle the lengths in advance. Also seems likestrncatcould help you.b. But your code is pretty close to working, you just need to insert a space (and thereforememcpyto a later offset for each word, e.g.b+agg_len[idx]+idx)