2017年5月19日 星期五

C語言小抄

用snprintf模擬asprintf來處理字串相加
char* cstr;
int c = snprintf( NULL, 0, "%d * %d = %d", tmp, tmp, tmp*tmp );
cstr = new char[ c + 1 ];
snprintf( cstr, c + 1, "%d * %d = %d", tmp, tmp, tmp*tmp );

基本型態與跟指標的大小,結論就是sizeof(任意型態的指標)都是8bytes
printf("char : %d\n", sizeof(char)); //輸出1
printf("char*: %d\n", sizeof(char *)); //輸出8 (我用64bit的OS,因此address是8byte)
printf("int  : %d\n", sizeof(int)); //輸出1
printf("int* : %d\n", sizeof(int *)); //輸出8 (我用64bit的OS,因此address是8byte)