Error compiling a modularized program in c

1

I made a program that read strings of a file separated by - (hyphen) and saves each string in a position of a struct vector.

When compiling, it generates the following error message:

  

array type has incomplete element type

I searched the net and saw that a solution would be to write the struct implementation inside the structures.h file, however, I'd like to leave the implementation hidden, leaving only the prototypes in .h

Would it be possible?

Follow the code:

main.c

#include <stdlib.h>
#include "estruturas.h"

int main()
{
    String vetor_de_string[MAX];
    leArquivo(vetor_de_string);

    return 0;
}

structures.h

#ifndef ESTRUTURAS_H_
#define ESTRUTURAS_H_
#define MAX 50

typedef struct string String;

void leArquivo(String *s);

#endif

structures.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "estruturas.h"

struct string
{
    char nome[20];
};

void leArquivo(struct string *s)
{
    FILE *f;

    f = fopen("data.txt", "r");

    if(!f)
    {
        printf("*** Erro: Nao foi possivel abrir o arquivo! ***\n");
        exit(1);
    }

    int l = 0, i = 0;
    char aux, a[20], b[20], c[20];

    while((aux = fgetc(f)) != EOF)
    {
        if(aux == '\n')
            l++;
        if(l > 0)
        {
            fscanf(f, "%19[^-]s", a);   
            aux = fgetc(f); 
            fscanf(f, "%19[^-]s", b);
            aux = fgetc(f);
            fscanf(f, "%19[^\n]s", c);

            strcpy(s[i].nome, a);
            strcpy(s[++i].nome, b);
            strcpy(s[++i].nome, c);
            i++;
        }
    }
    fclose(f);
}
    
asked by anonymous 04.06.2016 / 04:57

1 answer

0

It is impossible to construct a vector of a type without knowing the size of the type, because the size of the vector is the size of each element multiplied by the number of elements. In structures.c it is known that every String has a size of 20, but in main.c , then it is impossible to know what the size of vetor_de_string . So either you have to set struct string to the header, or you have to use only pointers to the type. (You know the size of a pointer to a type, without needing to know the size of the type.) For example, you can modify the argument type from leArquivo() from String* to String** and add the following:

structures.h

String *novaString();

structures.c

String *novaString() {
    return malloc(sizeof(struct string));
}

and uses novaString() in main() to allocate the vector:

int i;
String *vetor_de_string[MAX];
for (i = 0; i < MAX; i++) {
    vetor_de_string[i] = novaString();
}

Then, if you are not finishing the program soon, you must deallocate the elements of vetor_de_string :

for (i = 0; i < MAX; i++) {
    free(vetor_de_string[i]);
}
    
04.06.2016 / 10:04