Home > Mobile >  C is not printing my valid variable value
C is not printing my valid variable value

Time:06-27

I have a new typedef struct and an init function for it.

#include <stdlib.h>
#include <stdio.h>

typedef struct PERSON
{
  char * name;
  char * surname;
  int month;
  int day;
} * Person;

Person init_person(char * name, char * surname, int month, int day)
{
  Person person = calloc(1, sizeof(Person));
  person->name = name;
  person->surname = surname;
  person->month = month;
  person->day = day;
  return person;
}

int main(int argc, char * argv[])
{
  Person person = init_person("Hello", "World", 12, 12);
  
  printf("\n%s\n", person->name);
  printf("\n %i %i \n", person->month, person->day);
  return 0;
}

When the code is run, the expected output should be:


Hello

12 12


But instead, I am getting:

Hello

0 1769108595

When I swap around the printf function statements, I do get the desired output. I have written similar code using structures before but I have not faced such a problem. Could it be a memory problem?

CodePudding user response:

See Is it a good idea to typedef pointers? TL;DR — No, except perhaps for function pointers or pointers to opaque types, neither of which is relevant here.

And the problem is that you've been suckered into allocating insufficient memory by the pointer typedef. You have:

Person person = calloc(1, sizeof(Person));

That allocates enough space for one pointer to a struct PERSON. You need to use something equivalent to:

Person person = calloc(1, sizeof(*person));

to allocate enough space for what person will point to.

Or you need to remove the pointer from the typedef and make corresponding changes to the code. That will be better in the long run.

CodePudding user response:

You don't want to declare your structure as a pointer,

typedef struct PERSON
{
  char * name;
  char * surname;
  int month;
  int day;
} Person;

And if you need to make it a pointer,

Person *person = (Person *) malloc(sizeof(Person));
  • Related