【发布时间】: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) 我尝试了许多修复但无济于事的错误。
【问题讨论】:
-
您应该在尝试调用函数之前声明它们。您不应该转换
malloc或realloc的结果。 -
你也应该用“gcc -Wall”编译,因为你有很多警告
-
强制转换
realloc的结果不是一个好习惯。原因this answer解释的很清楚。 -
这很有趣,从来不知道 void 已经覆盖了它。谢谢!