Two-dimensional array size within the struct in C

0

Hello. I'm doing a job that I read a txt (the file name is passed by argv []) and it generates a graph. In the first line of the file two parameters are passed as follows: GO These parameters are integers and have a meaning: V = number of vertices, A = number of edges. Until then, beauty, I can get those numbers. The problem is to play these numbers on the size of the struct's two-dimensional float array. It needs to be something like "adj [numeroVertices] [numeroVertices]".

typedef struct Grafo{
    int numeroArestas;
    int numeroVertices;
    float **adj;
} Grafo;

int main(int argc, char *argv[]) {
    int numVertices, numArestas;

    FILE *f;
    f = fopen(argv[1], "r");
    fscanf(f, " %i %i", &numVertices, &numArestas);

    Grafo g;
    g.numeroArestas = numArestas;
    g.numeroVertices = numVertices;
    // g.adj = ???????
 ...
}
    
asked by anonymous 20.03.2016 / 17:29

1 answer

1

With C99 you can use VLA ( Variable Length Arrays ). But attention not to abuse the sizes!

    FILE *f;
    f = fopen(argv[1], "r");
    fscanf(f, "%i%i", &numVertices, &numArestas);
    int adj[numeroVertices][numeroVertices];      // VLA, C99
    // usa adj

If you can not use this feature, you have to turn to malloc() and friends

    int **adj, k;
    FILE *f;
    f = fopen(argv[1], "r");
    fscanf(f, "%i%i", &numVertices, &numArestas);

    adj = malloc(numVertices * sizeof *adj);
    if (adj == NULL) /* erro! */;
    for (k = 0; k < numVertices; k++) {
        adj[k] = malloc(numArestas * sizeof **adj);
        if (adj[k] == NULL) /* erro! */;
    }

    /* usa adj como um array */

    /* libertar recursos */
    for (k = 0; k < numVertices; k++) {
        free(adj[k]);
    }
    free(adj);
    
20.03.2016 / 19:56