因此,我尝试通过创建结构的动态数组在 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/