我不知道什麼是錯與此,它說不相容隱含建於FUNC 嗯,我沒有包括string.h中的文件,但它仍然給我一個錯誤錯誤的malloc使用C
int name_read;
int name_bytes = 100;
char *name;
printf("Please enter name:\n");
name = (char *)malloc(name_bytes + 1);
name_read = getline(&name, &name_bytes, stdin);
我不知道什麼是錯與此,它說不相容隱含建於FUNC 嗯,我沒有包括string.h中的文件,但它仍然給我一個錯誤錯誤的malloc使用C
int name_read;
int name_bytes = 100;
char *name;
printf("Please enter name:\n");
name = (char *)malloc(name_bytes + 1);
name_read = getline(&name, &name_bytes, stdin);
您需要#include <stdlib.h>
得到正確的聲明malloc
。
另外sizeof(name_bytes) + 1
看起來很腥;這會給你5個字節的內存,而不是你想象的那樣。
最後,不需要在C中返回malloc
的返回值,因爲它返回void*
。
#include <stdlib.h>
/* ... */
int name_bytes = 100;
char* name = malloc(name_bytes + 1);
要解決此錯誤,請確保您已包含stdlib.h。另外,你應該注意sizeof返回變量/類型的大小,而不是分配給變量的值。所以,你的sizeof(name_bytes)將返回以字節爲單位的整數的大小,而不是100
我覺得你確實需要name = malloc(name_bytes + 1);
(假設你要分配101個字節的名稱)
我最初是用它的函數getline忘了包括它,並不想讓它作爲void *返回 – 2011-03-26 01:58:50