PDA

View Full Version : Concatenate two array elements



b1
8th October 2007, 14:02
This is probably a dumb question but I am still learning so here goes....
I have a requirement to concatenate two elements of an array.

For example:


array[0] = "f";
array[1] = "e";
newarray[0] = "0x"+array[0]+array[1]

so the result would be "0xfe"

I have tried


char result[10];
char buffer[10];
sprintf( result[0] , "0x%c%c", (unsigned int) buffer[0], (unsigned int) buffer[1]);

which compiled but gave a segmentation error when run.

Any thoughts or suggestions would be greatly appreciated.

Thanks, B1.

jacek
8th October 2007, 14:17
If you are sure that newarray[0] is long enough, you can try:
strcat( newarray[0], array[0] );
strcat( newarray[0], array[1] );

Do you really need to operate on char *? QStrings are much safer.

b1
10th October 2007, 00:41
Thank you jacek. That solved my problem.

For the benefit of others here is my code:



char temp[10];
uint temp2;

strncat( temp, &array[0], 1);
strncat( temp, &array[1], 1);
sscanf( temp, "%x", &temp2);
newarray[0] = temp2;


Thanks again,

B1.

jacek
10th October 2007, 01:05
Remember to initialize temp.

Also if array is a zero-terminated string (according to your first post, it was supposed to be an array of char *), you don't need strncat() --- you can pass it directly to sscanf().

b1
28th October 2007, 04:59
Jacek,

I don't quite follow your suggestion

you don't need strncat() --- you can pass it directly to sscanf().

Wouldn't that pas the entire array to sscanf? I only want certain bits of it.

B1.

jacek
29th October 2007, 13:02
First of all, what is the exact type of "array"?

If "array" is an array of strings you can do this:
sscanf( array[0], "%x", &temp1 );
sscanf( array[1], "%x", &temp2 );
result = ( temp1 << 4*strlen(array[0]) ) + temp2;
this way you don't have to care about any temporary strings.

b1
29th October 2007, 20:43
Aaaahhhh,

The penny is starting to drop. I will have a play and see how I go. Thank you for the explanation, Jacek.

Regards, B1.