有人可以向我解釋為什么我對字符串大小為6的malloc的調(diào)用返回4個字節(jié)的sizeof嗎?實際上,我給malloc的任何整數(shù)參數(shù)都將得到sizeof4。接下來,我試圖復(fù)制兩個字符串。為什么我的輸出是復(fù)制的字符串(NULL)?以下是我的代碼:int main(){ char * str = "string"; char * copy = malloc(sizeof(str) + 1); printf("bytes allocated for copy: %d\n", sizeof(copy)); while(*str != '\0'){ *copy = *str; str++; copy++; } copy = '\0'; printf("%s\n", copy);}
3 回答

一只甜甜圈
TA貢獻1836條經(jīng)驗 獲得超5個贊
sizeof()返回變量實際類型的大小。因此,當(dāng)您將類型定義為char *時,它將返回指針的大小。
但是,如果您將變量設(shè)置為數(shù)組,則sizeof將返回數(shù)組本身的大小,這將實現(xiàn)您想要執(zhí)行的操作:
char *ptr = "moo to you";
char arr[] = "moo to you";
assert(sizeof(ptr) == 4); // assuming 32 bit
assert(sizeof(arr) == 11); // sizeof array includes terminating NUL
assert(strlen(arr) == 10); // strlen does not include terminating NUL
- 3 回答
- 0 關(guān)注
- 600 瀏覽
添加回答
舉報
0/150
提交
取消