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;
}
CodePudding user response:
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.
CodePudding user response:
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)
