c - Printing content of 2D array (pointer of pointer) -
i defined function initialising 2d array through pointers , @ same time fell random values.
then print , don't see expected values. bug in code? i've been looking hours.
#define matrix_size 3 int **initialize_matrix(size_t m, size_t n){ int i1,i2; int **ptr1=(int **)malloc(sizeof(int *)*m*n); int *ptr2=(int *)malloc(sizeof(int)*m); srand(time(0)); for(i1=0;i1<matrix_size;i1++){ for(i2=0;i2<matrix_size;i2++){ ptr2[i2]=rand()%10; printf("%d ",ptr2[i2]); } } for(i1=0;i1<matrix_size;i1++){ ptr1[i1]=ptr2+m*i1; } printf("\nfinished generating\n"); return ptr1; } void print_matrix(int** matrix_to_print){ int i1,i2; for(i1=0;i1<matrix_size;i1++) for(i2=0;i2<matrix_size;i2++){ printf("%d ",matrix_to_print[i1][i2]); if(i2==matrix_size-1) printf("\n"); } }
this prints:
2 4 8
0 6 7 6 4 4 finished generating matriz 1: 6 4 4
135113 0 0 0 0 0
sample code
#include <stdio.h> #include <stdlib.h> #include <time.h> #define matrix_size 3 int **initialize_matrix(size_t m, size_t n){ //make dynamic 2d array int a[m][n] int i1,i2; //there no need cast return value of malloc in c int **ptr1=(int **)malloc(sizeof(int *)*m); srand(time(0)); for(i1=0; i1<m; i1++){ ptr1[i1] = (int*)malloc(sizeof(int)*n); for(i2=0; i2 < n; i2++){ ptr1[i1][i2]=rand()%10; printf("%d ",ptr1[i1][i2]); } } printf("\nfinished generating\n"); return ptr1; } void print_matrix(int** matrix_to_print, size_t m, size_t n){ int i1,i2; for(i1=0;i1<m;i1++){ for(i2=0; i2<n; i2++) printf("%d ", matrix_to_print[i1][i2]); printf("\n"); } } int main(){ int **p = initialize_matrix(matrix_size, matrix_size); print_matrix(p, matrix_size, matrix_size); { //deallocate int i; for(i = 0; < matrix_size; ++i) free(p[i]); free(p); } return 0; }
Comments
Post a Comment