0

I have an array of integers and an array of chars.

int A[5] = {12, 23, 12, 32, 12};
char B[5] = {'a', 'e', 'd', 'y', 'i'};

I want to concatenate the two in order into a new array called

char P[5]; 

I want to output to be

p[5] =  {12a, 23e, 12d, 32y, 56i}

So far I tried using snprintf but it runs into segment fault and abort trap 6. Is there a simpler way to do this ?

6
  • 1
    1) [4] --> [5] 2) char P[4]; --> char *P[5]; Commented May 25, 2017 at 17:30
  • You need [5] in the array declarations for A, B and P, since each one will be storing five elements. snprintf is probably the simplest solution without using a non-standard library. Could your array sizing be the cause of your segfault? Commented May 25, 2017 at 17:32
  • @user234461 : not sure, could you write up a little function that could help me out please Commented May 25, 2017 at 17:33
  • 3
    like this Commented May 25, 2017 at 17:48
  • @BLUEPIXY beautiful !!! Commented May 25, 2017 at 17:55

1 Answer 1

2

You cannot have a char array storing values like '12e' at each index, you need a 2D-char array (which is an array of strings). You can use sprintf for data type conversion.

int A[5] = {12, 23, 12, 32, 12};
char B[5] = {'a', 'e', 'd', 'y', 'i'};
char P[5][15];
int i = 0;
for(i = 0; i < 5; ++i)
{
    sprintf(P[i], "%d%c",A[i],B[i]);
    printf("%s ",P[i]);
}

output: 12a 23e 12d 32y 12i

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

2 Comments

If you want to simplify, replace the first 4 lines in the for loop with sprintf(P[i],"%d%c",A[i], B[i]);
That's cool. Updated my answer accordingly. Thank you Justin.

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.