【问题标题】:C function call with struct array使用结构数组调用 C 函数
【发布时间】:2017-03-29 00:06:18
【问题描述】:

因此,我尝试通过创建结构的动态数组来在 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) 我尝试了许多修复但无济于事的错误。

【问题讨论】:

  • 您应该在尝试调用函数之前声明它们。您不应该转换 mallocrealloc 的结果。
  • 你也应该用“gcc -Wall”编译,因为你有很多警告
  • 强制转换realloc 的结果不是一个好习惯。原因this answer解释的很清楚。
  • 这很有趣,从来不知道 void 已经覆盖了它。谢谢!

标签: c arrays struct


【解决方案1】:

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

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

【讨论】:

  • 您好,感谢您的回复,我之前实际上已经尝试过该修复,但随后它被错误替换:struct node** init(struct node* * strarray) 行
  • 更改返回语句本身,而不是我的答案@IsaacChan 中所述的函数定义,因为我编译它并没有收到错误
  • 你的函数声明是同一行?即 struct node ** init(struct node ** strarray) 因为我将 return 语句更改为 return strarray;现在我得到了类型冲突的错误。你介意发布你要编译的代码吗?我会尝试看看是否有任何我可能没有注意到的差异
  • 没关系,我在这个问题上花了 7 个小时,我才意识到在整个过程中,我从来没有初始化过这个函数......
  • 对不起,我确实也声明了函数头@IsaacChan
猜你喜欢
  • 2012-02-13
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
相关资源
最近更新 更多