How to concatenate a char array case [0] and [1] to a char pointer in C? -


i want concatenate 2 characters '7' , '9' form string "79".

first, initialized variables. (restriction: have use char types , must not make charac alike variable.)

char *charac = (char *) malloc(sizeof(char) * 200); char *combined = (char *) malloc(sizeof(char) * 200); 

then gave values charac[0] , charac[1].

charac[0] = '7'; charac[1] = '9'; printf("charac[0] : %c\n", charac[0] ); printf("charac[1] : %c\n", charac[1] ); 

i want concatenate charac[0] , charac[1]

strcpy(combined, (char*)charac[0]); strcat(combined, (char*)charac[1]); printf("combined : %s\n", combined); free(combined); 

but code above doesn't work. got error message: "warning: cast pointer integer of different size".

after reading of comments , suggestions, obtain output result want.

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

they concatenated is. because right next each other in memory. have declared them in same array, , @ adjacent indexes.

+---------------+ |  '7'  |  '9'  | +---------------+    [0]     [1] 

this array in memory. 7 (charac[0]) right next 9 (charac[1]). suggested in comments, null terminate array complete concatenation.

charac[2] = '\0'; 

the array printf() friendly null terminated.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -