0

If I were to run this program right here.

#include <stdio.h>
#define SIZE 3

struct member
{
  char firstname[30];
  char lastname[30];
  char phone[10];
  int age;
};

int main()
{
  struct member members[] = {
      {
          "Martha",
          "Flores",
          "5576380918",
          20
      },
      {
          "Carolina",
          "Fuentes",
          "5510101010",
          21
      },
      {
          "Fernanda",
          "Ramos",
          "7778189054",
          23
      }};

  for (int i = 0; i < SIZE; i++)
  {
    printf("%s %s %s %d\n", members[i].firstname, members[i].lastname, members[i].phone, members[i].age);
  }

  return 0;
}

To output is going to be as expected + a weird character on the second result:

Martha Flores 5576380918 20
Carolina Fuentes 5510101010� 21
Fernanda Ramos 7778189054 23

Now, if I remove the field age from the structure and rewrite the program accordingly to get the same behavior.

#include <stdio.h>
#define SIZE 3

struct member
{
  char firstname[30];
  char lastname[30];
  char phone[10];
  // int age;
};

int main()
{
  struct member members[] = {
      {
          "Martha",
          "Flores",
          "5576380918",
          // 20
      },
      {
          "Carolina",
          "Fuentes",
          "5510101010",
          // 21
      },
      {
          "Fernanda",
          "Ramos",
          "7778189054",
          // 23
      }};

  for (int i = 0; i < SIZE; i++)
  {
    printf("%s %s %s\n", members[i].firstname, members[i].lastname, members[i].phone);
    // printf("%s %s %s %d\n", members[i].firstname, members[i].lastname, members[i].phone, members[i].age);
  }

  return 0;
}

I got this output:

Martha Flores 5576380918Carolina
Carolina Fuentes 5510101010Fernanda
Fernanda Ramos 7778189054���

Clearly I'm doing something wrong initializing the array, I tried being more specific while initializing the elements on the array with {.firstname = "", .lastname="", ...} but got the same result.

I'm compiling it with GCC

1 Answers1

1

Your phone numbers are actually 11 characters long, since they include the NUL terminating character ('\0'). You need to provide the proper amount of space.

For example, these two character strings are equivalent.

char n[] = "5576380918";
char m[] = { '5', '5', '7', '6', '3', '8', '0', '9', '1', '8', '\0' };

Simply provide more space for your phone numbers:

struct member {
    char firstname[30];
    char lastname[30];
    char phone[11];
    int age;
};

The random characters you are seeing is an indeterminable result of Undefined Behavior from reading past the end of your allocated space, since the printf function relies on strings to be properly NUL terminated.

Oka
  • 23,367
  • 6
  • 42
  • 53