1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* t(unsigned short menu_number)
{
char * ret = "Folder num ";
short x = strlen(ret);
/*
char *n = (int *)malloc(sizeof(char) * x + sizeof(short) ); // size = 11 + 2 = 13,
// but error convert (int *) to (char *)
strcpy(n, ret);
char *inn = (int *)malloc(sizeof(short)); // size = 2 * 4 = 8 bytes ,
// but error convert (int *) to (char *)
memcpy(inn, (char*)&menu_number, sizeof(unsigned short)); // inn: high_byte?, low_byte?,?,?,?,?,?,?
// bad idea
strcat(n, inn); // 11+8 > 13 overflow?
*/
// Changed !
char *n = (char *)malloc(sizeof(char) * (x + 7)); // unsigned short has max. 6 digit,
//+1 for '\0'
sprintf(n, "%s%d", ret, menu_number); // simple way to convert a number to string
return n;
}
int main(void)
{
printf("%s\n", t(2));
printf("%s\n", t(65535));
return 0;
}
| |