0

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)

5
  • 5
    Conceptually, joining the strings "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 like strncat could help you. Commented Jan 20, 2015 at 3:23
  • You need to measure the lengths in advance so you know how much memory to allocate to b. But your code is pretty close to working, you just need to insert a space (and therefore memcpy to a later offset for each word, e.g. b+agg_len[idx]+idx) Commented Jan 20, 2015 at 3:29
  • Thanks to @MattMcNabb , but I failed with that. The offset I added is not working correctly. Commented Jan 20, 2015 at 3:54
  • check your code and make sure you are using the right offset. Maybe walk through the code in a debugger, or on paper, checking your numbers. Commented Jan 20, 2015 at 3:55
  • thanks! I will find out where the problem is! thanks for your advice, @5gon12eder. Commented Jan 20, 2015 at 4:59

3 Answers 3

1

One solution would be to find the number of strings (num) in the array and make the new array have an extra length of num - 1 so that when you compose the message, simply add the spaces after you finish copying each word.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, the total length of the new array needs to be the sum of the N lengths plus N (not N-1) as you need a terminating null byte too.
1

Make enough buffer and use strcat. Space shoud be put for except last.

#include <stdio.h>
#include <string.h>

int
main(int argc, char* argv[]) {
  char *a[]={"I", "LOVE", "C", "PROGRAMMING"}; 
  char buf[1024] = {0};
  int i, len = sizeof(a)/sizeof(a[0]);
  for (i = 0; i < len; i++) {
    strcat(buf, a[i]);
    if (i < len - 1)
      strcat(buf, " ");
  }
  printf("[%s]\n", buf);
  return 0;
}

Probaly, your want is sizeof(a)/sizeof(a[0]) ?

If you must use **a instead of *a[]

#include <stdio.h>
#include <string.h>

int
main(int argc, char* argv[]) {
  char *a[] = {"I", "LOVE", "C", "PROGRAMMING", NULL}; 
  char buf[1024] = {0}, **p = a;
  while (*p) {
    strcat(buf, *p);
    if (*p && *(p + 1))
      strcat(buf, " ");
    p++;
  }
  printf("[%s]\n", buf);
  return 0;
}

5 Comments

It works! but my a array actually is char **a, that's why I don't use sizeof(a)/sizeof(a[0]). Is there another way to get the len? The length of a is unknown, so I use char **a to realloc each step.
If you must use **a instead of *a[], you have to put NULL into the array, and a[i] is NULL or not.
@user2722174: What do you mean 'my a array actually is char **a'? That's not what you showed in the question. For a char **, you have two options: (1) the calling code tells you how many entries are in the array, or (2) the last entry in the array is a special value, conventionally the NULL pointer.
To @JonathanLeffler, what I showed in the question is trying to know how to add spaces. So I make a simple example. But in my data, I need to split the input string to a. So I use char **a to realloc each step when I split input str and copy to a. according to the steps, I have already know the len of a,Thanks to you!!
@Shinline: congratulations on choosing a user name. That means, I think, that you have option (1) of the two I outlined — you know from some other source (calling function or whatever) how many entries are in the char **a array.
0
#include <stdio.h>
#include <string.h>

int main(void){
    char *a[]={"I", "LOVE", "C", "PROGRAMMING"};
    size_t a_size = 4;
    size_t width[a_size], total_size = 0;

    for(int i=0; i<a_size; i++){
        total_size += (width[i] = strlen(a[i]));
    }
    char b[total_size + a_size];//between ' '(a_size-1) + NUL(1)
    char *p = b;
    for(int i=0; i<a_size; ++i){
        if(i)
            *p++ = ' ';//put space
        memcpy(p, a[i], width[i]);
        p += width[i];
    }
    *p = '\0';//put NUL
    printf("'%s'\n", b);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.