Radex
Radex

Reputation: 8587

C signal: segmentation fault (core dumped)

I am learning C, and I am facing this error. Why I cannot pass a pointer to the funcion as change(&p_x); and only change(&x); works? Thanks

#include <stdio.h>

void change(int *p_xa) // GET ERROR HERE signal: segmentation fault (core dumped)
{
    *p_xa = 999;
}
    
int main()
{
    int x = 1;
    int * p_x = &x;

    *p_x = 2;

    change(&p_x); // cannot do this

    printf("x is: %d \n", *p_x);

    return 0;
}

Upvotes: 0

Views: 251

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 224082

change has a parameter of type int *.

The call passes &p_x. The type of p_x is int *. The type of &p_x is int **. That is the wrong type for the parameter. Passing &p_x passes the address of p_x, but you want to pass the address of x.

Pass p_x, not &p_x. The value of p_x is the address of x.

Enable warnings in your compiler and elevate them to errors. With Clang, start with -Wmost -Werror. With GCC, start with -Wall -Werror. With MSVC, start with /W3 /WX. When you do this, the compiler will warn you when an argument is an incorrect type for a declared parameter.

Upvotes: 6

stefanarctic
stefanarctic

Reputation: 34

Since you're taking a pointer as a parameter, you must also pass it when you call the function(you are passing the pointer of the pointer)

Upvotes: 0

Related Questions