gpt4 book ai didi

c - 我应该如何将此整数数组传递给这个函数?

转载 作者:行者123 更新时间:2023-12-02 09:35:44 25 4
gpt4 key购买 nike

对于这项作业,我的教授给了我们以下函数头:

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 *'

如果我是对的,它需要一个指向整数指针的常量数组?我应该如何处理我的条目数组才能使其成为有效参数?

我尝试过通过引用(&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 显然缺少这样的意图 指针到指针。由于 elementsconst,签名告诉我 thisFunc 不会修改 elements 后面的数据。同时,通过使用指针,签名告诉我它将修改 elements 本身,这看起来不像函数要执行的操作,因为 elements > 在别处阅读。

关于c - 我应该如何将此整数数组传递给这个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26492806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com