[英]C Compiler Errors - Warning: Assignment makes integer from pointer without a cast | Error: Subscripted value is neither array nor pointer
解答:我沒有正確初始化變量。
我需要記住指針聲明在C中的工作方式。
該代碼段應采用以下格式的某些命令行參數:
./foo 1 2 3 4 5 6 7 8 9 10 ...(只要能被5整除的任何合理數目的參數
我的計划是要有5個可變大小的int數組,以存儲參數供以后在邏輯中使用。 因此,如果我有10個參數,我將有5個2 -int數組,依此類推。
int* IP1, IP2, BID, PN, EID;
int i;
if((argc < 2) || ((argc-1) % 5) != 0)
{
/* Some error statements */
}
IP1 = (int*)malloc(argc-1);
IP2 = (int*)malloc(argc-1); //This is line 26
BID = (int*)malloc(argc-1);
PN = (int*)malloc(argc-1);
EID = (int*)malloc(argc-1);
for(i = 0; i < argc-1; i+=5){
IP1[i] = argv[i+1];
IP2[i] = argv[i+2]; //This is line 33
BID[i] = argv[i+3];
PN[i] = argv[i+4];
EID[i] = argv[i+5];
printf("%d\t", i);
}
問題是,我得到這些奇怪的錯誤
>cc foo.c -o foo
foo.c: In function ‘main’:
foo.c:26: warning: assignment makes integer from pointer without a cast
foo.c:27: warning: assignment makes integer from pointer without a cast
foo.c:28: warning: assignment makes integer from pointer without a cast
foo.c:29: warning: assignment makes integer from pointer without a cast
foo.c:33: error: subscripted value is neither array nor pointer
foo.c:34: error: subscripted value is neither array nor pointer
foo.c:35: error: subscripted value is neither array nor pointer
foo.c:36: error: subscripted value is neither array nor pointer
而且我不知道它們應該是什么或代表什么。 我查了一下,到目前為止沒有任何幫助。 我希望你們都能。
編輯:根據記錄,我嘗試注釋掉26-30和33-37行,並且編譯良好。 只是想我為后代補充。
這個:
int* IP1, IP2, BID, PN, EID;
與此相同:
int *IP1;
int IP2;
int BID;
...
你要這個:
int *IP1, *IP2, *BID, *PN, *EID;
但更一般而言,請嘗試避免在同一行上聲明多個變量。
您的變量IP2, BID, PN, EID
僅具有類型int
而不是int*
。 您必須在每一個前面寫*
。
您的方法存在以下問題: *
僅綁定到直接位於其下方的變量。 所以
int *intptr, intvar;
創建了一個指針,指向一個int
和類型的變量int
。 要同時擁有兩個指針,應編寫:
int *intptr, *intptr2;
//for more clarity
int *intptr;
int *intptr2;
或者(閱讀評論!):
typedef int* intptr;
intptr IP1, IP2, BID, PN, EID;
用C語言術語,聲明如下所示:
type-specifier declaration-specifiers;
類型說明符是一個單獨的類型,在您的情況下為int
。 其后是聲明說明符 ,這是逗號分隔的聲明 符列表。 聲明符不僅由聲明的標識符組成,還包括所有*
, []
和()
以使聲明看起來像其用法。 通過這種解釋,您顯然可以聲明
int* IP1, IP2, BID, PN, EID;
這是一個*IP1
,它是一個指向int的指針,其余的都聲明為ints。 這就是為什么經驗豐富的C程序員建議選擇其中一個原因的原因之一
*
移向聲明符中的標識符 這就是我寫聲明的方式:
int *IP1, *IP2, *BID, *PN, *EID;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.