[英]How should I pass this integer array in to this function?
對於此作業,我的教授給了我們以下函數頭:
void thisFunc(Node** root, const int * elements[], const int count)
大概這是正確的,我無法更改。
Const int * elements是用scanf獲取的int值的數組; 我宣布與我
int entries[atoi(argv[1])-1];
並成功填充
for(int a=0; a < atoi(argv[1]); a++) {
scanf("%i", &entries[a]);
}
但是我在打電話給thisFunc時很掙扎。
thisFunc(&bst, entries, atoi(argv[1]));
這會引發明顯的錯誤:
note: expected 'const int **' but argument is of type 'int *'
如果我是對的,期望有一個指向int指針的常量數組。 我應該如何處理我的entrys數組以使其成為有效參數?
我已經嘗試通過引用(&entries)傳遞條目,但是我有點迷茫。
簽名意味着您將把一個指針傳遞給一個指針,這又建議動態分配(而不是可變長度數組):
// Read the length once, and store it for future reference.
// Calling atoi on the same string multiple times is inefficient.
int len = atoi(argv[1]);
int *entries = malloc(sizeof(int) * len);
... // Populate the data in the same way, but use len instead of atoi(argv[1])
...
// Now you can take address of entries
thisFunc(&bst, &entries, len);
...
// Do not forget to free memory allocated with malloc once you are done using it
free(entries);
注意:這樣說,我幾乎可以肯定,您的教授在聲明thisFunc
犯了一個小錯誤,應該這樣聲明:
void thisFunc(Node** root, const int elements[], const int count)
我認為這應該是正確的簽名的原因是,在使變量成為指針之后需要有一種意圖,而使elements
成為const
指向指針的指針顯然缺少這種意圖。 由於elements
是const
,因此簽名告訴我thisFunc
不會修改elements
后面的數據。 同時,通過使用指針,簽名告訴我它將修改elements
本身,這看起來不像函數要做什么,因為elements
是在其他地方讀取的。
如果要使用提到的函數修改數組entry []中的值,則將調用更改為:thisfunc(&bst,&entries,atoi(argv [1]));
問題是您正在傳遞“ entries”,它是一個數組,但是您的函數需要一個指向int array []的指針。 因此,通過條目“&entries”的添加。
您是否嘗試過隱式轉換?
(const int**)variable;
完成;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.