我是一個初學者C.分配int存儲?
main() {
int *a-ptr = (int *)malloc(int);
*a-ptr = 5;
printf(「%d」, *a-ptr);
}
的問題是:這是保證打印5?
答案是:NO,原因有二:
- 不能使用 「 - 」 中的變量名
- 「你不分配int型存儲」
我不明白第二點。這行不是分配的存儲空間嗎?
int *a-ptr = (int *)malloc(int);
我是一個初學者C.分配int存儲?
main() {
int *a-ptr = (int *)malloc(int);
*a-ptr = 5;
printf(「%d」, *a-ptr);
}
的問題是:這是保證打印5?
答案是:NO,原因有二:
我不明白第二點。這行不是分配的存儲空間嗎?
int *a-ptr = (int *)malloc(int);
main() { // wrong. Should return int
int main() { // better
int *a-ptr = //wrong. no dashes in variable names
int *a_ptr = // better, use underscores if you want to have multiparted names
(int *)malloc(int); // wrong. Don't typecast the return of malloc(), also it takes a
// size, not a type
malloc(sizeof(int)); // better, you want enought memory for the sizeof 1 int
所以一個更好的版本的你的代碼是:
int main() {
int *a_ptr = malloc(sizeof(int));
*a_ptr = 5;
printf("%d", *a_ptr);
free(a_ptr); // When you're done using memory allocated with malloc, free it
return 0;
}
malloc
接受大小而不是類型。你需要做malloc(sizeof(int))
。
'malloc(sizeof * aptr)'...... – 2012-12-17 19:33:49
您的代碼由於多種原因無效,因此無法編譯。
a-ptr
是無效的變量名稱。 -
未在允許的名字, 使用a_ptr
代替(或其他)
malloc
並不需要一個類型。它需要一個大小(以字節爲單位)分配給 。
請務必使用直引號"
而不是使用的卷標引號 。
正確的代碼應該是這樣的:
int main() {
int *aptr = (int *) malloc(sizeof(int));
*aptr = 5;
printf("%d", *aptr);
return 0;
}
(從malloc
至int *
轉換可以是可選的,這取決於你的編譯器)
有些地方可以在這裏拍攝,因爲你敢用'main()'而不是'main(void)'或'main(int argc,char ** argv )' – ShinTakezou
@ShinTakezou我不熟悉C的複雜性 - 你能解釋一下還是提供一個鏈接? – ceyko
我只是對我產生了諷刺意味,因爲我有時會因爲使用'int main()'(我有理由寧願違反任何合理性)而被「攻擊」(正確地說,不要誤會),而不是'int main(void)'。簡單的事實是,標準(至少,C99 std)不會考慮int main()正確;這在語法上是允許的(出於歷史原因?),但根據某人的說法,它應該被刪除(或std需要以另一種方式改變,以允許'int main()'真正意味着'int main(void)',雖然目前他們不同...)。忘記它,或搜索主原型:) – ShinTakezou
也許,很難說。什麼是'malloc(int)'應該是什麼意思? –
此程序保證不打印5. –
@JamesMcNellis:實現選擇接受的不良形式程序的行爲完全由實現定義。所以它不是*保證*不做任何事情;-) –