I cannot do anything w/ matrices in C, and I cant find my mistake. Below is my code. It basically uses two functions, one to dynamically allocate a matrix, and another to initilaze the matrix w/ all zeros! The main program basically just allocates the all zero matrix, and then it prints it. This is a very small and simple program. It compiles w/ no warnings whatsoever. When I run the program it says access violation.
If I do a[0][0], no problems, where a is a float**. If I do a[1][1] then I get access violation. The funny thing is I have seen tons and tons of code that takes a float** and accesses it as if it were a float[][]. So, I must be missing something.
Code:#include<stdio.h> #include<stdlib.h> float** newmtrx(int, int); //Allocate space for matrix return pointer void initmtrx(float**, int, int); //set all entries to zero void main() { float** a; int i=0,j=0; a = newmtrx(5,5); //allocate and point to 5x5 matrix initmtrx(a,5,5); //set values in a to zero for(i=0; i<5; i++) for(j=0; j<5; j++) printf("%f\t",a[i][j]); } //end of main //function definitions float** newmtrx(int m, int n) { int i; float **p; p=(float **)malloc((unsigned) (m)*sizeof(float*)); if (!p) printf("Failure in allocate_real_matrix()."); for (i = 0; i < m; i++){ p=(float **)malloc((unsigned) (n)*sizeof(float*)); if (!p[i]) printf("Failure in allocate_real_matrix()."); } return p; } void initmtrx(float** a, int m, int n) { for(;m>0;m--) for(;n>0;n--) a[m-1][n-1] = 0; }