c - Declaring and accessing 2D array -
how can use array pointer (int *) create , print 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 have 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; < row; i++) { for(j = 0; j < column; j++) { *(matrix) = + j; matrix++; } } puts("success!"); } int printmatrix(int * matrix, int row, int column) { puts("begin printing matrix!"); int i, j, valuesprinted; for(i = 0; < row; i++) { for(j = 0; j < column; j++) { printf("%5d ", *(matrix + * 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 want is: use declare array , assign pointer, pass pointer function , give values above. think problem in way initialize 2d array pointer , access it.
and 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
int *matrix = malloc(sizeof(int) * row * column); // better written int *matrix = malloc((row*column) * sizeof *matrix);
the above statement dynamically allocates array of integers of size row * column
. if want access elements of array access elements of 2d array, element @ row i
, column j
has index
i * column + j
modify printmatrix
function -
int printmatrix(int * matrix, int row, int column) { puts("begin printing matrix!\n"); int i, j, valuesprinted; for(i = 0; < row; i++) { for(j = 0; j < column; j++) { // equivalent , more readabable // printf("%5d ", matrix[i*column + j]); printf("%5d ", *(matrix + i*column + j)); // ^ note multiplied column valuesprinted++; } puts(""); } puts("printing success!\n"); return valuesprinted; }
Comments
Post a Comment