Sebastian Bauer
Sebastian Bauer

Reputation: 37

random value in twodimensional array in c

Okay so, I have a twodimensional array of int's, which in create using this:

int **matrix;
matrix = malloc(n * sizeof(int*));
for (int i = 0; i < n ; i++) {
    matrix[i] = malloc(sizeof(int));
}

Now I set every field to 0. The next step is to fill it with values. Therefore I read values from a file I already opened.

while (fscanf(f2, "%s -> %[^;\n]%*c", start, ziel) == 2) {
    intomatrix(start, ziel, &graph);
}

intomatrix just alters the data and puts it in the matrix using

matrix[start][ziel] = 1;

Now when I set manually (not using the while-loop)

matrix[2][0] = 1

and print the matrix. Not only is (2,0) but also (0,4) set to 1. There should be now way in which matrix[0][4] is used.

This also happens with other fields. (2,0) also sets (1,4).

Upvotes: 1

Views: 45

Answers (1)

Dko
Dko

Reputation: 830

Should this:

matrix[i] = malloc(sizeof(int));

be an array of integers vs. just one? If not you have multiple rows but just one column.

Upvotes: 2

Related Questions