Reputation: 129
How can I use array pointer (int *) to create and print this kind of 2d array:
0 1 2 3 4 5 6 7 8...
1 2 3 4 5 6 7 8 9...
2 3 4 5 6 7 8 9 10...
3 4 5 6 7 8 9 ...
4 5 6 7 8 9...
5...
I currently have this code:
#include <stdio.h>
#include <stdlib.h>
void createMatrix(int * matrix, int row, int column)
{
puts("Begin creating matrix.");
int i, j;
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
*(matrix) = i + j;
matrix++;
}
}
puts("Success!");
}
int printMatrix(int * matrix, int row, int column)
{
puts("Begin printing matrix!");
int i, j, valuesPrinted;
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
printf("%5d ", *(matrix + i * j));
valuesPrinted++;
}
puts("");
}
puts("Printing success!");
return valuesPrinted;
}
int main()
{
int row = 11;
int column = 13;
int * matrix = malloc(sizeof(int) * row * column);
createMatrix(matrix, row, column);
printMatrix(matrix, row, column);
return 0;
}
What I want to do is: use declare array and assign to pointer, then pass the pointer to a function and give it values as above. I think the problem is in the way I initialize the 2D array by pointer and access it.
And the result is:
0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9 10 11 12
0 2 4 6 8 10 12 2 4 6 8 10 12
0 3 6 9 12 3 6 9 12 3 6 9 12
0 4 8 12 4 8 12 4 8 12 4 8 12
0 5 10 3 8 13 6 11 4 9 14 7 12
0 6 12 6 12 6 12 6 12 6 12 6 12
0 7 2 9 4 11 6 13 8 15 10 17 12
0 8 4 12 8 4 12 8 16 12 8 16 12
0 9 6 3 12 9 6 15 12 9 18 15 12
0 10 8 6 4 14 12 10 8 18 16 14 12
Upvotes: 0
Views: 102
Reputation: 9680
int *matrix = malloc(sizeof(int) * row * column);
// could better be written as
int *matrix = malloc((row*column) * sizeof *matrix);
The above statement dynamically allocates an array of integers of size row * column
. If you want to access the elements of this array as you would access elements of a 2D array, then the element at row i
and column j
has the index
i * column + j
Modify your printMatrix
function to -
int printMatrix(int * matrix, int row, int column)
{
puts("Begin printing matrix!\n");
int i, j, valuesPrinted;
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
// this is equivalent and more readabable
// printf("%5d ", matrix[i*column + j]);
printf("%5d ", *(matrix + i*column + j));
// ^ note i is multiplied by column
valuesPrinted++;
}
puts("");
}
puts("Printing success!\n");
return valuesPrinted;
}
Upvotes: 2
Reputation: 2817
printf("%5d ", *(matrix + i * column + j));
instead of
printf("%5d ", *(matrix + i * j));
Upvotes: 1
Reputation: 753785
Your printing code is using the wrong expression to access the elements of the matrix. You've got:
printf("%5d ", *(matrix + i * j));
You need:
printf("%5d ", *(matrix + i * column + j));
Or:
printf("%5d ", matrix[i * column + j]);
Upvotes: 2