0

Why do I get Segmentation fault here? I'm very new to C and it's really hard for me. I googled much and found out that it have to be working normally.

#include <stdio.h>

struct school
{
    int schoolNum;
    int year;
    int gradNum;
    int univNum;
};

int main()
{
    struct school schools[5] = {
        114, 2020, 470, 300,
        86, 2019, 545, 450,
        231, 2020, 340, 320,
        113, 2020, 435, 395,
        55, 2019, 395, 380
    };

    printf('%d\n', schools[0].gradNum);

    return 0;
}
6
  • 1
    Use " instead of ' for string literals. Commented Jul 31, 2020 at 12:42
  • 2
    The single quotes in your printf call are wrong. use double quotes for your format string. You should get a compiler warnings about the problem. (Enable all warnings.) Commented Jul 31, 2020 at 12:42
  • thank you, that was really stupid mistake Commented Jul 31, 2020 at 12:44
  • 1
    You may also like to add 4 pairs of braces { ... } in your initializer array of structures. Commented Jul 31, 2020 at 12:46
  • 1
    A decent compiler should emit a warning about multi.character literals, and if not then you need to enable more warnings. Commented Jul 31, 2020 at 12:47

1 Answer 1

3

There's two errors in your code, as said in the comments, you need to replace single quotes by double quotes in your printf call. Then you need to add braces pairs to enclose each school instance, as below:

struct school schools[5] = {
        {114, 2020, 470, 300},
        {86, 2019, 545, 450},
        {231, 2020, 340, 320},
        {113, 2020, 435, 395},
        {55, 2019, 395, 380}
    };
Sign up to request clarification or add additional context in comments.

1 Comment

In fact, omitting the inner braces is not an error per se, but adding them highly recommended for readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.