我应该如何将此整数数组传递给此函数?

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的指针的常量数组?我应该如何处理将使其成为有效参数的条目数组?

我已经尝试通过引用(和条目)传入条目,但我有点迷失.

das*_*ght 8

签名意味着您将向指针传递指针,而指针又建议动态分配(而不是可变长度数组):

// 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在其他地方读取.

  • @Rohawk我几乎可以肯定你的教授犯了一个错误:他在`elements`前加了一个星号.您可以使用强制转换([demo](http://ideone.com/bznvPN)使用`const`双指针运行它但它没用:您无论如何都不应该修改条目,而您需要额外的在`myFunction`中取消引用.没有额外的星号,它更自然,并且不需要演员([另一个演示](http://ideone.com/vZNPGF)). (2认同)