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);