in Programming closed by
561 views
0 votes
0 votes
closed with the note: Error
what is wrong with this code? It shows segmentation fault

#include<stdio.h>
#include<stdlib.h>
void main()
{
    int i,j,count=1;
    int **a=(int**)malloc(3*sizeof(int*));
    for(i=0; i<3; i++)
    {
        a[i]=(int*)malloc(4*sizeof(int));
    }
    for(i=0; i<3; i++)
    {
        for(j=0; j<4; j++)
        {
            a[i][j]=count; count++;
        }
    }
    printf("\n");
    for(i=0; i<3; i++)
    {
        for(j=0; j<4; j++)
        {
            printf("%d ",a[i][j]);
        }
        printf("\n");
    }
}
in Programming closed by
by
561 views

4 Comments

@akshat16

it is for implementing a[3][4], so it should be there

0
0
your code is right too, but I merely want to say it can be furthur optimised

I mean second for loop is redundant

try this code

#include<stdio.h>
#include<stdlib.h>
void main()
{
    int i,j,count=1;
    int **a=(int**)malloc(3*sizeof(int*));
    for(i=0; i<3; i++)
    {
        a[i]=(int*)malloc(4*sizeof(int));
    
        for(j=0; j<4; j++)
        {
            a[i][j]=count; count++;
        }
    }
    printf("\n");
    for(i=0; i<3; i++)
    {
        for(j=0; j<4; j++)
        {
            printf("%d ",a[i][j]);
        }
        printf("\n");
    }
    return 4;
}
0
0
ok... so your comment is on optimization.
0
0

1 Answer

0 votes
0 votes
instead of writing of void main() plz write the int main();

1 comment

That doesn't matter here.
0
0

Related questions