oke I was coding some stuff involving 2d array allocating i normally know how to do it in main coz you don't need to pass adr main ptr that get's allocated but when i made it i got somewhat confused I don't know why it went wrong

#include <stdio.h>
#include <windows.h>
BOOL AllocateMemory(int ***iArray,int rows,int cols) {
     *iArray = (int**)calloc(rows,sizeof(int));
     if(!*iArray)
         return false;
     for(int i =0;i < cols;i++) {
         **iArray = (int*)calloc(cols,sizeof(int));
         if(!**iArray)
             return false;
     }
     return true;
}
void FreeAllocated(int **iArray,int rows,int cols) {
     for(int i = 0; i < rows;i++) {
         for(int x = 0;x < cols;x++)
              free(*iArray);
         free(iArray);
     }
     return;
}
              
void ShowArr(int **iArray,int rows,int cols) {
     for(int i = 0; i < rows;i++)
     for(int x = 0 ; x < cols ;x++)
         printf("%d\n",iArray[i][x]);
}

int main(void)
{
    int **iArray;
    if(AllocateMemory(&iArray,3,3)) {
       ShowArr(iArray,3,3);
       FreeAllocated(iArray,3,3);
    }
    getchar();
    return 0;
}

ShowArr should show all 0 but it shows first i made allocating ptr to ptr then after that in loop i made allocate ptr to int only which should be right ..

The allocate and free of your inner loops are wrong.

BOOL AllocateMemory(int ***iArray,int rows,int cols) {
     *iArray = calloc(rows,sizeof(int[B]*[/B]));
     if(!*iArray)
         return false;
     for(int i =0;i < rows;i++) {
         (*iArray)[i] = calloc(cols,sizeof(int));
         if( !(*iArray)[i] )
             return false;
     }
     return true;
}
void FreeAllocated(int **iArray,int rows,int cols) {
     for(int i = 0; i < rows;i++) {
          free( iArray[i] );
     }
     free(iArray);
     return;
}

I can only assume from the chaotic mix of keywords that you're using C++ to compile this C code.

anyways thanks i get where did i go wrong stupid me :D since i m allocating my inner array as rows i should have went i < rows not i < cols
thanks it works now.

This article has been dead for over six months. Start a new discussion instead.