So I'm trying to do some practice in C by trying to create a dynamic array of structs, but I'm running into some difficulty when trying to pass the struct into different functions for different operations.
My code so far:
#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);
}
}
I haven't worked on the printarray method yet, I'm trying to get the function declaration and the pass to work. Currently, I'm getting a conflicting types for ‘init’ struct node** init(struct node** strarray) error which I have tried many fixes to, but no avail.