HB-*_*HB- 2 c pointers parameter-passing
对于这项任务,我的教授给了我们以下函数头:
void thisFunc(Node** root, const int * elements[], const int count)
Run Code Online (Sandbox Code Playgroud)
据推测,这是正确的,我无法改变这一点.
Const int*elements是一个使用scanf获取的int值数组; 我和我一起宣布了
int entries[atoi(argv[1])-1];
Run Code Online (Sandbox Code Playgroud)
并成功填充它
for(int a=0; a < atoi(argv[1]); a++) {
scanf("%i", &entries[a]);
}
Run Code Online (Sandbox Code Playgroud)
但我正在努力调用thisFunc.
thisFunc(&bst, entries, atoi(argv[1]));
Run Code Online (Sandbox Code Playgroud)
这引发了明显的错误:
note: expected 'const int **' but argument is of type 'int *'
Run Code Online (Sandbox Code Playgroud)
如果我是对的,它期待一个指向int的指针的常量数组?我应该如何处理将使其成为有效参数的条目数组?
我已经尝试通过引用(和条目)传入条目,但我有点迷失.
签名意味着您将向指针传递指针,而指针又建议动态分配(而不是可变长度数组):
// 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);
Run Code Online (Sandbox Code Playgroud)
注意:有了这个说法,我几乎可以肯定你的教授在声明时犯了一个小错误thisFunc,并且它应该被声明为:
void thisFunc(Node** root, const int elements[], const int count)
Run Code Online (Sandbox Code Playgroud)
我认为,这应该是一个正确的签名的原因是,需要有背后做一个变量的指针的意图,这种意图显然是作出缺少elements一个const指针到指针.由于elementsIS const,签名告诉我,thisFunc是不会落后修改数据elements.同时,通过使用指针,签名告诉我它将elements自己修改,这看起来不像函数将要做的,因为elements在其他地方读取.