programmmm
programmmm

Reputation: 19

MacOS programming C delivers error: zsh: segmentation fault

As described in the heading, the terminal delivers the error: zsh: segmentation fault. Here is the - pretty basic - code:

#include<stdio.h>

int main(){
    int age = 0;
    printf("Input your age!");
    scanf("%d", &age);
    printf(age);
}

thanks for the help solving this problem :)

Upvotes: 0

Views: 776

Answers (1)

ProgrammerPerson123
ProgrammerPerson123

Reputation: 61

printf(age);

should be printf("%d", age);

You need to pass in a string literal (eg: "hello world") with a format specifier (exactly the same way you did it in scanf) and then pass the age (not its address as you did with scanf, so without the &) as a second argument. for example

printf("I am %d years old\n", age);

For the above example, I printed a message that writes "I am [age] years old" and then continues down to a new line (that's the '\n'). The '%d' is a format specifier; what it does is it specifies that in its position, the function should print a value of a specific type (%d specifies an integer). You can have multiple of these specifiers and it prints the arguments you give it in linear order. I would highly recommend you look at this[1], it should explain it better than I can.

Upvotes: 2

Related Questions