I'm a beginner to C and came across a segmentation fault, which is what I understand as to be the program trying to access restricted or unavailable area of memory.
This issue is occurring for me in a function:
void process_command(struct pizzeria *the_pizzeria, char *command) {
if (command[0] == 'n') {
struct order **last_next_order_field = get_last_next_order_field(the_pizzeria);
*last_next_order_field = create_order();
}
if (command[0] == 's') {
//Line below receives error
get_integer_input(the_pizzeria->selected_order, "");
}
}
which is linked to this other function:
void get_integer_input(int *variable, char *prompt) {
printf(prompt);
scanf("%d", variable);
getchar();
}
It must be noted that these functions are relating to this struct:
#define PIZZERIA_NAME_LENGTH 16
#define PIZZERIA_OWNER_LENGTH 16
struct pizzeria {
char name[PIZZERIA_NAME_LENGTH];
char owner[PIZZERIA_OWNER_LENGTH];
int selected_order;
struct order *orders;
};
I don't understand why when passing the_pizzeria->selected_order
in get_interger_input
in the function process_command
makes pointer from integer without a cast as in my past functions of getting a char input instead I use the same process and don't receive an error.
I also set variable as a pointer so I don't understand the note produced by the terminal:
note: expected ‘int *’ but argument is of type ‘int’
void get_integer_input(int *variable, char *prompt)
CodePudding user response:
You don't show us these "past functions", but I assume that they ask the user for name or owner. These elements of your struct are arrays, and if you pass their name as an argument it decays to a pointer to the first element.
In contrast, the integer is not an array. Therefore, you need to pass its address like this:
if (command[0] == 's') {
get_integer_input(&the_pizzeria->selected_order, "");
}
If you are not very firm with operator precedence, better use parentheses:
if (command[0] == 's') {
get_integer_input(&(the_pizzeria->selected_order), "");
}
The compiler is correct with its diagnostic message. You pass an integer, but the functions needs a pointer.