Two-dimensional array size within the C-struct

Asked

Viewed 141 times

0

Hello. I am doing a job I read a txt (the file name is passed by argv[]) and I write a graph. In the first line of the file two parameters are passed as follows: V A These parameters are integers and have a meaning: V = number of vertices, A = number of edges. So far, beauty, I can get these numbers. The problem is to throw these numbers in the size of the two-dimensional array of struct floats. 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 = ???????
 ...
}

1 answer

1


With C99 you can use VLA (Variable Length Arrays). But beware 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 cannot use this feature, you have to resort 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);
  • Thanks! Just one question: on this line "adj[k] = malloc(numArestas * size of **adj)" am I making it a square array? That is, if I pass a Vertices = 4, at the end of the for I will have a 4x4 array?

  • You can use the final object as if it were a 4x4 array (but it is not a true array). In that part of the /* usa adj como um array */ you can put anything like that: for (k = 0; k < 4; k++) { adj[k][0] = 0.8; adj[k][1] = -3.14; adj[k][2] = adj[k][3] = 0; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.