C/memory allocation
Expert: Prince M. Premnath - 5/3/2007
Question Hi,
How are you? I am trying to write a program that operates with large arrays. The code below initializes my array but there seems to be a problem. I got my pointers wrong I think because I can not write values into the newly initialized array. I am very new with pointers. I'd be very thankful if you could look at the code and suggest how I could write values into and out of the matrix I created. Thankfully, Tom.
#include <stdio.h>
#include <string.h>
int main()
{
int nrows = 200;
int ncolumns =300;
int *i;
int *matrx = (int *) malloc(nrows*sizeof(int));
for (i=0; i<nrows; i++)
matrx[i] = (int *) malloc(ncolumns*sizeof(int));
matrx[2][2] = 5;
printf("%d
", matrx[2][2]);
free(matrx);
return 0;
}
AnswerHi dear Mr TOM
I found lot of bugs with your code specially in allocating memory for the two dimensional array !
Here im presenting you the code that meet your request , if you wish you can alter this code !
#include<stdio.h>
#define maxr 400
#define maxc 400
void main()
{
int i;
int n;
int *matrix[maxr];
int nrows =200 , ncols =300;
for( i = 0 ; i <= nrows ; i )
matrix[i] = (int*) malloc( ncols *sizeof(int));
matrix[2][2] = 20;
printf("
matrix[2][2]);
free(matrix);
}
THanks and regards !
Prince M. Premnath