简体   繁体   中英

Strange values on a 2-d integer C array

I know this is probably a very simplistic fix, but I have spent an hour googling and trying to fix it to no avail. This is the code in the beginning of main. Nothing else manipulates the graph[][] array. Its very simple C code. I am trying to initialize a 2-d integer array, and set all values to 0. But Later values end up being strange, random numbers. I know this happens when you don't initialize every value. BUT I am, and I ran through GDB and confirmed that it went through my test 4X4 array and initialized everything to 0. I am stumped.

printgrapharray is just a double for loop to go through every slot...

code:

#include <stdio.h>

#define inputarraylength 200
#define MAXVERTICES 100

void printgrapharray(int graph[][MAXVERTICES], int vertamount);

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

    int numvert = 1;
    char edges[inputarraylength];
    char vertices[inputarraylength];

    freopen("input.txt", "r", stdin);

    scanf("V={%[^}]s", vertices);

    printf("\nVERTICES\n");
    printf("%s\n", vertices);            //comma-seperated list of names

    for (int i = 0; i < inputarraylength; i++) {

        if (vertices[i] == ','){

            numvert++;                          //get number of vertices
        }
    }
    const char *verts[numvert];         //create vertice array

    printf("numvert: %d\n", numvert);

    int graph[numvert][numvert];                    //create n*n matrix array

    for (int k = 0; k < numvert; k++) {
        for (int z = 0; z < numvert; z++) {

            graph[k][z] = 0;                            //init the graph 2-d array slots to 0
        }
    }
    printgrapharray(graph, numvert);
}

output:

VERTICES
Aa, Bbb, Cccc, Ddddd
numvert: 4

ADJACENCY MATRIX!
0 0 0 0 
0 0 0 0 
1562140139 32767 1562140159 32767 
774977075 1163132977 1398754642 1230197573 

You declare the printgrapharray function like

void printgrapharray(int graph[][MAXVERTICES], int vertamount);

which means the argument graph is a pointer to arrays of MAXVERTICES integers.

When you call the function you pass the main local variable graph to it, which will decay to a pointer to arrays of numgraph integers. Unless MAXVERTICES and numgraph are equal, you have a mismatch in the types, and that will lead to undefined behavior .

This problem is something the compiler should have detected, and given you a warning about.


There is actually a simple solution to this, because C has variable-length arrays: Use the argument vertamount in the declaration of the graph argument:

void printgrapharray(int vertamount, int graph[][vertamount]);

Note that the order of the arguments had to be switched, because vertamount must be declared before it is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM