0

I am trying to make a program which basically only uses structs. It is basically a single soccer match... Below is my code:

#include <stdio.h>

/* Structs Definitions */

typedef struct {
  int day;
  int month;
  int year;
} date;

typedef struct {
  char name[16];
  int goals;
} teams;

typedef struct {
  date date;
  teams teams[2];
} match;

/* Function Definitions */

void startMatch() {
  match match;

  /* Day that the match happened */
  match.date.day = 22;
  match.date.month = 11;
  match.date.year = 2022;

  /* Defining results of the match */
  int pos = 1;
  for (int teams = 2; teams > 0; teams--) {
    printf("Nome do %dº time: ", pos);
    scanf(" %15s", match.teams[pos].name);

    printf("Gols na Partida: ");
    scanf(" %i", &match.teams[pos].goals);

    pos++;
  }
}

int main(void) {
  startMatch();
  return 0;
}

My input when running the code is:

Japan 2 Germany 1

I was expecting no error, and the structure match was suposed to contain the struct date, and the struct with 2 elements so i can compare them later.

stack smashing detected ***: terminated

Please, what am i doing wrong?

Raul Chiarella
  • 518
  • 1
  • 8
  • 25
  • 1
    You seem to have forgotten that array indexes are based on *zero*. So an array of two elements will have indexes `0` and `1`. Remembering that, please explain your loop to your [rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging). – Some programmer dude Nov 24 '22 at 19:09
  • As for the loop, why not use `for (int teams = 0; teams < 2; teams++)` and use `teams` as the index (and skip `pos` altogether)? That's how most people would do it. – Some programmer dude Nov 24 '22 at 19:12
  • For more information on stack smashing, take a look at this SO answer: https://stackoverflow.com/a/1347464/ – Dash Nov 24 '22 at 19:33

0 Answers0