You are here:

C/memory allocation

Advertisement


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;
}

Answer
Hi 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise


I'm sure that I can solve any doubts in Turbo C ,Graphics Programing ,Mouse, Hardware Programming ,File System ,Interrupts, BIOS handling , TSR Programming , General Concepts in C Language, handling inline Assembly statements

Experience

Research over 6+ Years

Organizations
CG-VAK Softwares and Exports Limited

Education/Credentials
Masters in Computer Applications

©2012 About.com, a part of The New York Times Company. All rights reserved.