473,396 Members | 1,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

concatenating elements of an array

15
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 = "abcdefghijklmno".
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]
Dec 26 '08 #1
14 15438
JosAH
11,448 Expert 8TB
Have a look at the strcat() function.

kind regards,

Jos
Dec 26 '08 #2
donbock
2,426 Expert 2GB
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.
Dec 27 '08 #3
boddah
15
man...segmentation 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
Dec 31 '08 #4
JosAH
11,448 Expert 8TB
@boddah
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.

Expand|Select|Wrap|Line Numbers
  1. int calc_length(char** msg, int msglen) {
  2.    int sum;
  3.    for (sum= 0; msglen--; sum+= strlen(*msg++));
  4.    return sum;
  5. }
  6. char* catenate(char** msg, int msglen, char* dst) {
  7.    char* p;
  8.    for (p= dst; msglen--; strcpy(p, *msg++), p+= strlen(p));
  9.    return dst;
  10. }
  11.  
kind regards,

Jos
Dec 31 '08 #5
boddah
15
@JosAH
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.
Dec 31 '08 #6
JosAH
11,448 Expert 8TB
@boddah
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
Dec 31 '08 #7
boddah
15
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?
Jan 14 '09 #8
vekipeki
229 Expert 100+
What is pcr if I may ask?
Check the last line, where you used "pcr" instead of "cr":

Expand|Select|Wrap|Line Numbers
  1. unsigned char a[20] = "test"; 
  2. char cr[21];
  3. strncpy(cr, (char*)a, 20);
  4. printf("aha:%s\n", cr);
  5.  
Jan 14 '09 #9
boddah
15
ah..yes, no prob. it's supposed to be cr. my typo
@vekipeki
Jan 14 '09 #10
donbock
2,426 Expert 2GB
@boddah
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.

Expand|Select|Wrap|Line Numbers
  1. /* Notice use of "char", not "unsigned char" */
  2. char *a;
  3. char *msg[5] = {
  4.      "abc", "def", "ghi". "jkl", "mno" };
  5. const int nmsgs = 5;
  6. size_t len;
  7. int i;
  8.  
  9. /* compute length of concatenated string (plus 1 for terminating null */
  10. len = 0;
  11. for (i=0; i<nmsgs; i++)
  12.    len += strlen(msg[i]);
  13. /* allocate output buffer */
  14. a = malloc(len+1);
  15. if (a == NULL) {
  16.    handle the out-of-memory error
  17. }
  18.  
  19. /* Initialize output buffer to 'empty' */
  20. a[0] = '\0';
  21. /* concatenate each msg entry in turn */
  22. for (i=0; i<nmsgs; i++)
  23.    strcat(a,msg[i]);
  24. /* print the result */
  25. printf("%s\n", a);
  26. ...
  27. /* Don't use pointer after the buffer is freed */
  28. free(a);
Jan 14 '09 #11
Tassos Souris
152 100+
Just a little note for the above code:
Expand|Select|Wrap|Line Numbers
  1. malloc( ... * sizeof( char ) );
  2.  
Well, it is a good habit to use that
Jan 14 '09 #12
JosAH
11,448 Expert 8TB
@Tassos Souris
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
Jan 14 '09 #13
Tassos Souris
152 100+
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,realloc (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!
Jan 14 '09 #14
JosAH
11,448 Expert 8TB
@Tassos Souris
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
Jan 14 '09 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Unforgiven | last post by:
I have an application, where I continuously get new binary data input, in the form of a char*. This data comes from the Windows Multimedia wave input functions, but that's not important. What it...
1
by: Chi | last post by:
Hi There, The following is a popup form that works exactly as I want but I now need to get the values of each text box added when a user clicks the 'Add' button and pass the values back the...
4
by: Juan | last post by:
Does any one know if there are reported bugs when concatenating strings? When debugging each variable has the correct value but when I try to concatenate them some values are missing (I can´t see...
4
by: Richard L Rosenheim | last post by:
Is there any built-in method or mechanism for concatenating two arrays of byte together? I haven't come across anything to do this, and was just checking before I implement some code. Richard...
21
by: c | last post by:
Hi everybody. I'm working on converting a program wriiten on perl to C, and facing a problem with concatenate strings. Now here is a small program that descripe the problem, if you help me to...
1
by: Chris | last post by:
I am programatically binding a datasouce to a dropdown. It is the names of employees that meet certain criteria. In the database they are stored as forename and surname. Aside from concatenating...
4
by: jtanz0 | last post by:
Hi, I am trying to convert infix notation to postfix notation, so far i have been quite successfull but in order to move on to the next part of the program (RPN calculator) i need to take all the...
2
hsriat
by: hsriat | last post by:
I have an array, and I want to suffix "0" to the first 10 elements and "1" to the remaining array elements. So what I did was: First.for($i=0; $i<count($set_name); $i++) $set_name .= $i < 10 ?...
17
by: eBob.com | last post by:
I know it wouldn't be hard to write, but I have been unable to find a method which will take elements of a character array and concatenate them into a string. I've looked at both String members...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.