The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
0 votes
175 views
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");
    }
}
closed with the note: Error
in Programming by Active (4.3k points)
closed by | 175 views
+1

a small mistake

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

should be replace by

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

0
terrible mistake :D
working fine now
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

@akshat16

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

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
ok... so your comment is on optimization.

1 Answer

0 votes
instead of writing of void main() plz write the int main();
by Active (1.8k points)
0
That doesn't matter here.

Related questions

0 votes
1 answer
5
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,984 questions
55,135 answers
190,487 comments
85,105 users