Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

is my dynamically allocation of 2D array correct ?

include<stdio.h>

include<stdlib.h>

include<string.h>

main()
{
int a,b,i,j,k=0;
scanf("%d %d", &a,&b);
int (*ptr)[b];
ptr = malloc( sizeof(int[a][b]) );

for(i=0;i<a;i++)
{
    for(j=0;j<b;j++)
    {
        ptr[i][j]=k;
        k++;
    }
}
for(i=0;i<a;i++)
{
    for(j=0;j<b;j++)
    {
       printf("%d\t",ptr[i][j]);
    }
       printf("\n");
}
free(ptr);
return 0;

}

Comments

  • Tyson BlairTyson Blair Member Posts: 35
    int sizeOfa = 10;
    int sizeOfb = 10;
    ptr = malloc( sizeof(int) * (sizeOfA * sizeOfb)  );
    //so this will allocate the memory for an array same as int c[10][10]; or maybe int c[9][9];
    
  • Tyson BlairTyson Blair Member Posts: 35

    the reason fo the sizeof(int) as int can be different sizes on different compilers so we make sure we allocate enough memory.

Sign In or Register to comment.