1
int main (int argc, char *argv[])
{
    int a, b, quo, rest;

    void division(int dividendo, int divisor, int *ptr_quociente, int *ptr_resto)
    {
        *ptr_quociente=dividendo/divisor;
        *ptr_resto=dividendo%divisor;
    }

    if(argc=3)
    {
        a= atoi(argv[1]);   
        b= atoi(argv[2]);    

        division(a,b,&quo,&rest);

        printf(" %d and %d \n",quo,rest);
    }
    else if (argc=1)
        do
        {
            printf("type two int numbers:\n");

            scanf("%d %d", &a, &b);

            division(a,b,&quo,&rest);

            printf(" %d and %d \n",quo,rest);

        } while(a!=0);
}

if I do:

./program.c 12 6

it works but if I do:

./program.c

I get a segmentation fault, why?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Bryant2
  • 49
  • 8

1 Answers1

2
 if(argc=3) should be if(3 == arc) //notice '=='

That's why it is always good idea to keep constant on LHS, this will avoid accidental assignment

Same with arc=1

Also, I moved local function definition outside main.

void division(int dividendo, int divisor, int *ptr_quociente, int *ptr_resto)

{

       *ptr_quociente=dividendo/divisor;
       *ptr_resto=dividendo%divisor;
}

int main (int argc, char *argv[])

{
...
}

Edit: After reading comments from Paxdiablo and Shafik, I came to know most modern compiler would warn for '=' in condition. You can simply write if(argc == 3) rather than placing constant on LHS.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31
  • Bah, that's what I like to call "butt-ugly format", especially since modern compilers can warn about assignments within conditionals. But +1 anyway since you found the problem, even as I laugh derisively at your solution :-) – paxdiablo Mar 05 '14 at 04:34
  • Ack no, [Yoda condition we need not use with a modern compiler](http://stackoverflow.com/questions/22106713/what-is-the-difference-between-if-null-pointer-vs-if-pointer-null). – Shafik Yaghmour Mar 05 '14 at 04:34
  • @paxdiablo Shafik, yes kind of agree, as it is defensive programming than anything else. if(arc == 3) should be fine. – Digital_Reality Mar 05 '14 at 04:37