concatenating elements of an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • boddah
    New Member
    • Dec 2008
    • 15

    concatenating elements of an array

    Hi all,
    I've been trying to get this working for days but I still couldn't get it.

    snippet:
    unsigned char *a;
    unsigned msg[5];

    I want to concatenate all 5 elements from array msg to the unsigned char *a.
    Lets say
    msg[0]="abc";
    msg[1]="def";
    msg[2]="ghi";
    msg[3]="jkl";
    msg[4]="mno";

    and in the end a would point to a value = "abcdefghijklmn o".
    I've tried the usuals but still unsuccessful. appreciate it if anyone could enlighten me on this. thanks.
    for(int i=0;int<5;i++)
    a = a + msg[i]
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Have a look at the strcat() function.

    kind regards,

    Jos

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Don't forget to allocate a big enough char buffer for the final string. You need to assemble the concatenation in a buffer and set a to point to that buffer.

      Comment

      • boddah
        New Member
        • Dec 2008
        • 15

        #4
        man...segmentat ion error..i cant figure it out. so i just use a short-cut. Write and append all those arrays to a file and then read 'em back as a string. thanks all

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by boddah
          man...segmentat ion error..i cant figure it out. so i just use a short-cut. Write and append all those arrays to a file and then read 'em back as a string. thanks all
          That's like going from Dallas to Fort Worth over New York; I don't call that a short cut ;-) First calculate the sum of the lengths of the strings plus one for the terminating \0 character. Find (malloc) yourself a char buffer of at least that size and copy those strings in, one after another.

          Code:
          int calc_length(char** msg, int msglen) {
             int sum;
             for (sum= 0; msglen--; sum+= strlen(*msg++));
             return sum;
          }
          char* catenate(char** msg, int msglen, char* dst) {
             char* p;
             for (p= dst; msglen--; strcpy(p, *msg++), p+= strlen(p));
             return dst;
          }
          kind regards,

          Jos

          Comment

          • boddah
            New Member
            • Dec 2008
            • 15

            #6
            Originally posted by JosAH
            That's like going from Dallas to Fort Worth over New York; I don't call that a short cut ;-) First calculate the sum of the lengths of the strings plus one for the terminating \0 character. Find (malloc) yourself a char buffer of at least that size and copy those strings in, one after another.

            Code:
            int calc_length(char** msg, int msglen) {
               int sum;
               for (sum= 0; msglen--; sum+= strlen(*msg++));
               return sum;
            }
            char* catenate(char** msg, int msglen, char* dst) {
               char* p;
               for (p= dst; msglen--; strcpy(p, *msg++), p+= strlen(p));
               return dst;
            }
            kind regards,

            Jos
            Thanks Jos...I've been using malloc and new but i always get a segmentation fault. I'm quite new to all this malloc and sizeof.

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by boddah
              Thanks Jos...I've been using malloc and new but i always get a segmentation fault. I'm quite new to all this malloc and sizeof.
              You either have to use malloc/free or new/delete, never use a combination thereof. Show us some of your latest code so we can see what's wrong ...
              (not the file stuff, show your version before that).

              btw, if you use my version and malloc/new as many bytes as the number returned by the first function you can safely call the second function that does the catenating job.

              kind regards,

              Jos

              Comment

              • boddah
                New Member
                • Dec 2008
                • 15

                #8
                man..i still can't solve this.

                unsigned char array[20];
                char cr[21];
                strncpy(cr, (char*)array,20 );
                printf("aha:%s\ n",pcr);

                -it still gives me segmentation fault. can someone pls help?

                Comment

                • vekipeki
                  Recognized Expert New Member
                  • Nov 2007
                  • 229

                  #9
                  What is pcr if I may ask?
                  Check the last line, where you used "pcr" instead of "cr":

                  Code:
                  unsigned char a[20] = "test"; 
                  char cr[21];
                  strncpy(cr, (char*)a, 20);
                  printf("aha:%s\n", cr);

                  Comment

                  • boddah
                    New Member
                    • Dec 2008
                    • 15

                    #10
                    ah..yes, no prob. it's supposed to be cr. my typo
                    Originally posted by vekipeki
                    What is pcr if I may ask?
                    Check the last line, where you used "pcr" instead of "cr":

                    Code:
                    unsigned char a[20] = "test"; 
                    char cr[21];
                    strncpy(cr, (char*)a, 20);
                    printf("aha:%s\n", cr);

                    Comment

                    • donbock
                      Recognized Expert Top Contributor
                      • Mar 2008
                      • 2427

                      #11
                      Originally posted by boddah
                      man..i still can't solve this.
                      Code:
                       unsigned char array[20];
                      char cr[21];
                      strncpy(cr, (char*)array,20);
                      printf("aha:%s\n",pcr);
                      -it still gives me segmentation fault. can someone pls help?
                      You shouldn't cast casually. Sometimes a cast is necessary, but often it is a sign that you're doing something you shouldn't.

                      This thread has gotten pretty long. I'm making a conscious decision to stop being coy. Please look at the following example code. Ask about the rationale for any differences from your code that you don't understand. There is plenty of room for further improvement.

                      Code:
                      /* Notice use of "char", not "unsigned char" */
                      char *a;
                      char *msg[5] = {
                           "abc", "def", "ghi". "jkl", "mno" };
                      const int nmsgs = 5;
                      size_t len;
                      int i;
                       
                      /* compute length of concatenated string (plus 1 for terminating null */
                      len = 0;
                      for (i=0; i<nmsgs; i++)
                         len += strlen(msg[i]);
                      /* allocate output buffer */
                      a = malloc(len+1);
                      if (a == NULL) {
                         handle the out-of-memory error
                      }
                       
                      /* Initialize output buffer to 'empty' */
                      a[0] = '\0';
                      /* concatenate each msg entry in turn */
                      for (i=0; i<nmsgs; i++)
                         strcat(a,msg[i]);
                      /* print the result */
                      printf("%s\n", a);
                      ...
                      /* Don't use pointer after the buffer is freed */
                      free(a);

                      Comment

                      • Tassos Souris
                        New Member
                        • Aug 2008
                        • 152

                        #12
                        Just a little note for the above code:
                        Code:
                        malloc( ... * [B]sizeof( char ) );[/B]
                        Well, it is a good habit to use that

                        Comment

                        • JosAH
                          Recognized Expert MVP
                          • Mar 2007
                          • 11453

                          #13
                          Originally posted by Tassos Souris
                          Just a little note for the above code:
                          Code:
                          malloc( ... * [B]sizeof( char ) );[/B]
                          Well, it is a good habit to use that
                          I'm in the opposite camp: sizeof(char) equals one by definition so there is no need to multiply by that number.

                          kind regards,

                          Jos

                          Comment

                          • Tassos Souris
                            New Member
                            • Aug 2008
                            • 152

                            #14
                            You are right Jos but i said: Well, it is a good habit to use that
                            With that i meant that it is not a must but something good to use cause (at least for me) it keeps remind me that when using malloc,calloc,r ealloc (or another memory allocation function from other libraries) i need that sizeof() thingy...
                            As i said just a habit i use! My bad not to explain that more thoroughly!

                            Comment

                            • JosAH
                              Recognized Expert MVP
                              • Mar 2007
                              • 11453

                              #15
                              Originally posted by Tassos Souris
                              You are right Jos but i said: Well, it is a good habit to use that
                              With that i meant that it is not a must but something good to use cause (at least for me) it keeps remind me that when using malloc,calloc,r ealloc (or another memory allocation function from other libraries) i need that sizeof() thingy...
                              As i said just a habit i use! My bad not to explain that more thoroughly!
                              Easy; no need to get upset about it ;-) feel free to multiply a number by one if you want; be my guest. The optimizer most likely removes that multiplication anyway. I'm just in the 'no news is good news' camp and C and verbosity don't mix well (by tradition).

                              kind regards,

                              Jos

                              Comment

                              Working...