具有两个指针的 C 函数

标签 c function pointers reference

您好,我的一个功能有问题。声明如下:

int load_clusters(char *filename, struct cluster_t **arr)

而且我不知道如何在 **arr 之前使用这两个指针。 我希望我这样调用它:

struct cluster_t *clusters;
load_clusters("file.txt",&clusters);

但我不确定这是否正确。

在函数中我需要为其分配内存。 我想应该是这样的。

 arr = (struct cluster_t**)malloc(count * sizeof(struct cluster_t*));
 arr[0...x] = (struct cluster_t*)malloc(sizeof(struct cluster_t));
 arr[0...x]->size += 1;
.
.
.

但毕竟我需要调用函数来打印簇。

 void print_clusters(struct cluster_t *carr, int narr)
{
    printf("Clusters:\n");
    for (int i = 0; i < narr; i++)
    {
        printf("cluster %d: ", i);
        print_cluster(&carr[i]); AND THIS DOESN'T WORK AS I EXPECT
    }
}

感谢所有帮助;-)

最佳答案

在函数 load_clusters 中,arr 是一个局部变量,因此对其所做的任何更改都不会反射(reflect)在调用方中。

您拥有的是要分配给的指针变量的地址。因此取消引用它并为 struct cluster_t 数组分配空间。

*arr = malloc(count * sizeof(struct cluster_t));

此外,don't cast the return value of malloc .

关于具有两个指针的 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848280/

相关文章:

c - 产生新进程 v 线程的动机

c - 数组和字符串之间的 char 大小不一致

python - python内部函数定义中的变量是什么?

function - 快速访问函数外部的变量

c++ - 全局指针由优化器解析 - 但引用不是 - 为什么?

c - C 标准对两个有符号整数的按位异或有何规定?

objective-c - 这可以缩短吗?字体=字体?字体 : defaultFont;

javascript - 我试图用 JS 更改 CSS "body"属性的背景...我一直收到控制台错误 "newBgColor is not defined"

c++ - 调用方法后应用程序崩溃

c - 将 *next 列表指针设置为 NULL