0

I am very new to programming in C, and can't seem to locate the cause of the segmentation error that I have been getting. The program I wrote is as follows:

# include <stdio.h>
# include <stdlib.h>

int recursive(int x){
    if(x=0)
    {
        return 2;
    }
    else
    {
        return 3*(x-1)+recursive(x-1)+1;
    }
}
int main(int argc, char *argv[])
{
    int N = atoi(argv[1]);
    return recursive(N);
}

I would appreciate any help.

Thanks a lot

1
  • 6
    should be if( 0 == x) Commented Sep 11, 2014 at 9:28

4 Answers 4

3
if(x=0){...}

it's wrong

It should be

if(x==0){...}

Note:

if (x = 0) 

is the same as: 

x = 0; if (x)
Sign up to request clarification or add additional context in comments.

Comments

2

This:

if(x=0){

is not a (pure) test, it's an assignment. It works in the if since it also has a value (zero), but it's always false so that branch is never taken, i.e. the recursion never stops.

You should enable all compiler warnings, this is very commonly caught by compilers.

Comments

2

Change if(x = 0) to if(0 == x)

It is a good rule of hand to write 0 == x instead of x == 0 because in case of a typo like = instead of == the compiler will give an error.

Comments

1

The segfault error is from the use of argv[1]. Make sure you call your function with an argument, as follow:

$ ./a.out 6

with a.out the name of your program, and 6 the number you want to apply the function on. The following line will create a segfault :

$ ./a.out

because the first argument isn't set.

Plus, watch out on the second line : use == instead of =

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.