使用struct数组调用C函数

时间:2017-03-29 00:06:18

标签: 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'获得一个冲突的类型 struct node ** init(struct node ** strarray) 我尝试过多次修复的错误,但没有用。

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,您需要对您返回的变量进行解除反馈。 做

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;
}
}