I want to concatenate two characters '7' and '9' to form this string "79".
First, I initialized the variables. (Restriction: I have to use char types only and I must not make another charac alike variable.)
char *charac = (char *) malloc(sizeof(char) * 200);
char *combined = (char *) malloc(sizeof(char) * 200);
Then I gave the values for charac[0] and charac[1].
charac[0] = '7';
charac[1] = '9';
printf("charac[0] : %c\n", charac[0] );
printf("charac[1] : %c\n", charac[1] );
I want to concatenate charac[0] and charac[1]
strcpy(combined, (char*)charac[0]);
strcat(combined, (char*)charac[1]);
printf("combined : %s\n", combined);
free(combined);
But the code above doesn't work. I got the error message: "warning: cast to pointer from integer of different size".
After reading all of your comments and suggestions, I obtain the output result I want.
Here is the final code:
char *charac = (char *) malloc(sizeof(char) * 200);
char *combined = (char *) malloc(sizeof(char) * 200);
charac[0] = '7';
charac[1] = '9';
charac[2] = '\0';
printf("charac[0] : %c\n", charac[0] );
printf("charac[1] : %c\n", charac[1] );
printf("charac[2] : %c\n", charac[2] );
strcpy(combined, & charac[0]);
strcat(combined, & charac[1]);
strcpy(combined, & charac[0]);
strcat(combined, & charac[2]);
printf("combined : %s\n", combined);
free(combined);
A string in C consists of the individual characters followed by a null (zero byte). So the string "79" is of length 3.
Strings are placed into character array storage. You can allocate it on the heap, but just declaring an array is simpler. So the code would be:
Even simpler:
Even simpler:
Each of these three pieces of code does exactly the same thing.
In response to a comment, the treatment of initialised aggregates in the C standard is defined as follows: n1570 S6.7.9/21:
In other words, any time you use brace initialisation the remaining items are zero filled.
They are already concatenated as is. This is because they are right next to each other in memory. You have declared them in the same array, and at adjacent indexes.
This is your array in memory. The seven (
charac[0]
) is right next to the nine (charac[1]
). As suggested in the comments, simplynull
terminate the array to complete the concatenation.The array is now
printf()
friendly as it is null terminated.