Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call by value in C

I'm new to programming and I am currently working on C.

I learned that C does not have call by reference. The programs that we write to pass the address of actual parameters to the formal parameters is also call by Value in C.

Correct me if I'm wrong.. However, I ran this program :

//Swapping of two numbers using functions. #include

void swap(int *,int *);

void main()
{
    int x,y;
    printf ("Enter the values of x and y : ");
    scanf("%d %d",&x,&y);

    swap(x,y);

    printf("The value of x = %d and y = %d",x,y);
}

void swap(int *a,int *b)
{
    int temp;

    temp=*b;
    *b=*a;
    *a=temp;
}

It compiles just fine.. however, I'm getting a Segmentation Fault in the Output.

It asks me the enter the value of X and Y and then gives, Segmentation fault..

Please help!!

like image 464
Dorjay Yolmo Avatar asked Dec 06 '25 08:12

Dorjay Yolmo


2 Answers

you are sending an int to a function that expects int*, thus when you are dereferencing - temp=*b; you are trying to access memory you don't own -> segfault. Call swap like this: swap(&x,&y);

like image 95
CIsForCookies Avatar answered Dec 08 '25 21:12

CIsForCookies


So close

swap(&x,&y);

You were not passing references (pointers)

like image 25
LoztInSpace Avatar answered Dec 08 '25 22:12

LoztInSpace