2

I would like to concatenate char array and the int array and store them in another char array. How could I do that?

Here is the code so far

char letter[100];
int number[100], i;

char * letterNum[100];

for (i = 0; i < 100; i++){
 letterNum[i] = strcat(letter[i], number[i]);
}

expected output should be

a1
b1
...

1
  • What is a string array? [Hint: you already told char array] Commented Jun 19, 2015 at 7:13

3 Answers 3

2

The strcat() function concatenates strings not chars, you need sprintf()

sprintf(letterNum[i], "%c%d", letter[i], number[i]);

and also, letterNum in your case is an array of pointers, it should be an array of arrays, like

char letterNum[100][3];

and then, you can use snprintf() instead of sprintf() to prevent buffer overflow

if (snprintf(letterNum[i], 3, "%c%d", letter[i], number[i]) > 2)
    youHaveToDoSomethin_An_Error_Occurred();
Sign up to request clarification or add additional context in comments.

Comments

1

I guess Mr. Iharob already answered your question, but just to elaborate a bit more,

Let's see the man page of strcat(). It says,

char *strcat(char *dest, const char *src);

which means it expects both the arguments to be pointer to strings. Now, as we know, a pointer to int array cannot be considered a string, we cannot use strcat() directly in your case.

So, what you have to do is,

  • Take another buffer
  • Copy both the contents of the char array and int array elements for particular index one after another in lexicographical format, so that the final result is the concatenation of both.

Now, you have sprintf()/ snprintf() to help you out in this case. It prints the formatted o/p to the supplied string.

A pseudo-code

char letter[100];   //populating value, not shown
int number[100];    //populating value, not shown

int i = 0;

char letterNum[100][32];

for (i = 0; i < 100; i++){
 if ( sprintf(letterNum[i], "%c%d", letter[i], number[i]) != 2)
             printf("Error in %d iteration\n", (i+1));
}

Comments

0

Thank you very much for your help! I guess, I need to try an error and test it out myself... the explaination was clear and helpful... plus given codes for me to eeasily understand... Your kind help is greatly aappreciated.. Thank you once again

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.