in Programming closed by
573 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
573 views

6 Comments

a small mistake

 a[i]=(int*)sizeof(4*sizeof(int));

should be replace by

 a[i]=(int*)malloc(4*sizeof(int));

1
1
terrible mistake :D
working fine now
0
0
Also there is no need of second  (for) loop of i,it will unnecessarily increase time of complexity and reduce readibility

 

ps:please excuse me if i am wrong and notify me
0
0

@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