Reputation: 1
I try to print out two arrays with the following function using XCode 6.1.1:
for (int j=0; j<4; j++) {
for (int k=0; k<4; k++) {
printf("%2d ", Lattice[0][j+N*k]);
}
printf(" ");
for (int k=0; k<4; k++) {
printf("%2d ", Lattice[1][j+N*k]);
}
printf("\n");
}
printf("\n");
Everything works fine when calling the function, as long as I don't print out a float before. When printing an int, there's no problem. So it's a little strange, right? I'm initializing the array like this:
int **Lattice = (int**)malloc(2*sizeof(int*));
if (Lattice == NULL) return NULL;
for (int i=0; i<2; i++){
Lattice[i] = (int *)malloc(2*sizeof(int));
if (Lattice[i] == NULL) {
for (int n=0; n<i; n++)
free(Lattice[n]);
free(Lattice);
return NULL;
}
else{
for (int j=0; j<N; j++) {
for (int k=0; k<M; k++) {
Lattice[i][j+N*k] = 0;
}
}
}
}
return Lattice;
Too bad, I can't upload an image of the output.
The matrices should show only zeros, but with the float there will be big numbers in some entries which i can't explain.
I'm grateful for any hints. Thank you.
Upvotes: 0
Views: 82
Reputation: 38909
So your code has some pretty serious problems.
Lattice[0]
and Lattice[1]
need to have dimensions 4x4 for your printing block of code to make any sense. Incidentally this means N
and M
need to equal 4 as well or you need to change your printing for
loop conditions to j < N
and k < M
respectively.
Your malloc
needs to allocate space for that as well, so: Lattice[i] = (int *)malloc(N * M * sizeof(int));
This should cause your loops to work correctly, but you do not have floats anywhere in your code. You cannot use printf
to print an int
as a float
. The value will not be promoted. It will simply be treated as a float
.
Upvotes: 1