LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   allocating memory (https://www.linuxquestions.org/questions/programming-9/allocating-memory-150595/)

eshwar_ind 02-25-2004 10:44 PM

allocating memory
 
Hi!
Can any body expalin me the way of allocating memory for a two dimensional array. I mean i will have a pointer(or double pointer) but i should allocate memory using malloc or calloc. When i am accesing data i should follow array indexing like a[1][2];

chewysplace 02-25-2004 11:21 PM

for(x = 0;x<20;x++)
for(y = 0;y<20;y++)
a[x][y] = 0;

like this?

or this? from: http://msdn.microsoft.com/library/de...crt_malloc.asp

#include <stdlib.h> /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>

void main( void )
{
char *string;

/* Allocate space for a path name */
string = malloc( _MAX_PATH );
if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
}

doraiashok 02-26-2004 04:17 AM

One of the ways to allocate memory for a double pointer is given in the code below,

Code:

// m is the no. of rows
// n is the no. of columns
int **matrix;
matrix = (int **) malloc(sizeof(int*)*m);
for(i=0;i<m;i++)
{
  matrix[i] = (int *) malloc(sizeof(int) * n);
}


eshwar_ind 02-26-2004 04:39 AM

Mr. can i access that array using
Matrix[i][j];

doraiashok 02-26-2004 05:50 AM

Of course you can access the array using Matrix[i][j],

Consider this example,

On the first allocation, let the address of Matrix be as below,

Matrix = 1004 (address value)

so, Matrix + 1 = 1008
Matrix + 2= 1012
...
Matrix + ( m - 1) = ...


now allocating each row,

Matrix[0] = *(Matrix+0) = 2000, (Let us assume some address)
Matrix[1] = *(Matrix+1) = 3000,
.... and so on

after above allocation,

Matrix[0], Matrix[1] ..... will point to the address of n integers.

so,

Matrix[0] + 1= *(Matrix+0)+1 = 2004 (These are addresses)
Matrix[0] + 2= *(Matrix+0)+2 = 2008
.... so on

now,

Matrix[1][1] = *(Matrix[1]+ 1) = *( *(Matrix+1)+1) = 10; (can store an integer value).

Hope you get it....
Thanx.

eshwar_ind 02-26-2004 05:57 AM

ok!
Thanks Mr. Ashok
I understood.
Once again thanks.

kev82 02-26-2004 07:06 AM

depending on what you want to do with the array a double pointer approach is not always the best, because if the array is nXm then each traversal requires n pointer dereferences where each may require a cache refill(if array is big), the amount of memory required to store the array is m*(n+1) if the datasize is the same as pointer size, however, substituting one row for another is no more than a single memory assignment. my preferred method is to create a 1d array m*n in size and access it like array(i,j)=array[i+j*n], traversal is much quicker and it takes less memory but row operations are much more difficult.


All times are GMT -5. The time now is 02:27 AM.