amarti44 (Programmer) Jun 6, 2001 
Please help me to understand this function to allocate a 2D array. 
int** ArrayAlloc(int rows, int cols, int size)
{
    int i;
    int** pp;
  
    pp = (int**) malloc(rows * sizeof(int*));
    /* check for error */
    pp[0] = (int*) malloc(rows * cols * size);
    /* check for error */   
    for(i = 1; i < rows; ++i)
        pp = &(pp[0][i * cols * size]);
    return pp;
} 
 
 
Zyrenthian (Programmer) Jun 6, 2001 
this does not look like it works and it is a bit confusing to read.  why not just declare the 2d array as 

int pp[rows][cols]... not in the function but in place of it?  

The above just changes the memory address of pp and does not assign it an int** but an int*.  

if you prefer you could:
 pp = &((int*)malloc(rows*cols*sizeof(int)));  

this will give you the same amount of memory allocated and you can do with it what you will.

Matt 
 
IonFilipski (Programmer) Jun 6, 2001 
I suggest you:
int* ArrayAlloc(int rows, int cols,ins size)
{
    int* pi;
    pi=(int*)malloc(rows*cols*size);
    return pi;
}
An R-dimentions space in computer memory will look always as 1Dimention array 
John Fill


ivfmd@mail.md
 
 
xGrob (Programmer) Jun 8, 2001 
to declare a 2 dimensional array in C using malloc, you have to do this:

int** pp;

for(int i = 0; i < 100; i ++)
   *(pp+i) = (int*)malloc(sizeof(int) * 100);

you have to allocate space for EVERY row in in the array

"pp = (int**) malloc(rows * sizeof(int*));" will only allocate space for ONE row, hence causing an error if you try to access a row greater than  pp[1][99] 
 
IonFilipski (Programmer) Jun 11, 2001 
Zyrenthian,
what does pp = &((int*)malloc(rows*cols*sizeof(int))); mean?
malloc returns a number, not a variable, and operator & there is at least unexpected.

xGrob, what does pp+i mean, have you forgotten what so far pp is a not initialized pointer to pointer? You'll generate so a memory crash.
correct is:
int**pp;
int* p;
int nRows=100;
int nColumns=10;
p=(int*)malloc(nRows*nColumns*sizeof(int));
pp=(int**)malloc(nColumns*sizeof(int*));
for(int i=0;i<nColumns;i++)
{
  pp=p[i*nColumns];
}

John Fill


ivfmd@mail.md
 
 

 E-mail This Thread To A Friend   
 Back To C   
 

 
 IonFilipski 
smaniraja 
Lim 
SwapSawe 
Zyrenthian 
ankan 
bluenote 
MemoryLeak 
Nosferatu 
rbobbitt 
(Full List) 
  
 

 
 C++: Microsoft 
Visual Basic(Microsoft) -Version 5 & 6 
Java (Sun) 
C++: UNIX 
Javascript 
More 
  
 

    
    
   
  
         Before you start Have you answered this question before?
Write your own C FAQ and point amarti44 to it!
(Members please login at left before posting.) 
Step 1
Choose Handle     The name by which you'll be known in the forums. 
Step 2
Message
 
 
 
 
