使用结构数组调用 C 函数

标签 c arrays struct

因此,我尝试通过创建结构的动态数组在 C 中进行一些练习,但在尝试将结构传递给不同的函数以进行不同的操作时遇到了一些困难。

到目前为止我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
char *str;
int len;
};
//& gives address of value, * gives value at address
int main(void) {
    struct node **strarray = NULL; 
    int count = 0, i = 0;

    printf("hello\n");
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    /* allocate memory for one `struct node` */
    strarray[count] = (struct node *)malloc(sizeof(struct node));

    strarray = init(strarray);  
    return 0;
}

struct node ** init(struct node ** strarray){ //this is the line that's causing problems

    int i = 0, count = 0;
    char line[1024];

    if(fgets(line, 1024, stdin) != NULL) {
        /* add ONE element to the array */
        strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

        /* allocate memory for one `struct node` */
        strarray[count] = (struct node *)malloc(sizeof(struct node));

        /* copy the data into the new element (structure) */
        strarray[count]->str = strdup(line);
        strarray[count]->len = strlen(line);
        count++;
        return **strarray;
    }

}
void printarray(){
    for(i = 0; i < count; i++) {
        printf("--\n");
        printf("[%d]->str: %s", i, strarray[i]->str);
        printf("[%d]->len: %d\n", i, strarray[i]->len);
    }
}

我还没有研究过 printarray 方法,我正在尝试让函数声明和传递起作用。目前,我得到了“init”的冲突类型 结构节点**初始化(结构节点** strarray) 错误,我尝试了很多修复,但无济于事。

最佳答案

你的问题是你取消引用了你要返回的变量。 做

return strarray

代替

return **strarray

这是整个函数:

struct node ** init(struct node ** strarray){

int i = 0, count = 0;
char line[1024];

if(fgets(line, 1024, stdin) != NULL) {
    /* add ONE element to the array */
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    /* allocate memory for one `struct node` */
    strarray[count] = (struct node *)malloc(sizeof(struct node));

    /* copy the data into the new element (structure) */
    strarray[count]->str = strdup(line);
    strarray[count]->len = strlen(line);
    count++;
    return strarray;
}
}

关于使用结构数组调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082025/

相关文章:

c - 为什么我不能为该指针数组元素分配 NULL 值?

常量的 C 字符串连接

python - 我可以在 Python 列表中创建 "view"吗?

javascript - 如何使用jquery在选择框选项中显示数据

c - 在 C 中试验指针和数组

c - 使用 fwrite 将结构存储在文件中

c++ - 什么语言创造了左值这个术语?

c - 正在跳过一个特定的变量引用

c - 将结构体的地址分配给指针

c# - 将 C++ 结构转换为 C# 结构