-2
typedef struct Std{
    char* name;
    char* surname;
    int yearOfBirth;
} Std;
[...]
Std* obj = (Std*)calloc(1, sizeof(Std));
scanf("%s", obj->name);
scanf("%s", obj->surname);
scanf("%d", obj->yearOfBirth);

Dont work. How make scanf save the strings to the structure's fields?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
KanekiSenpai
  • 122
  • 10
  • "Dont work" is not a very good problem description. You need to allocate space for the strings that `name` and `surname` point to. As they stand, their values are undefined and they're invalid pointers. Then you need to provide the address of `obj->yearOfBirth` for that `scanf` to work: `scanf("%d", obj->yearOfBirth);` --> `scanf("%d", &obj->yearOfBirth);`. – lurker Jun 02 '20 at 00:45

1 Answers1

2

With calloc () you allocated for obj the memory space needed by Std structure. But with this action you are not allocating the two char * pointers it contains: name and surname.

Accessing them with scanf means writing to undefined location, and this probably leads to a segmentation fault.

So, just malloc () to them enough space to contain name and surname:

typedef struct Std{
    char* name;
    char* surname;
    int yearOfBirth;
} Std;

Std* obj = calloc(1, sizeof(Std));
obj->name = malloc(50*sizeof char);
obj->surname = malloc(50*sizeof char);

scanf("%49s", obj->name);
scanf("%49s", obj->surname);

Some notes:

  • In C, casting the result of malloc is not required. It is instead required in C++, so you can omit it unless you are using a C++ compiler
  • sizeof char is 1. I added it to hilight the type ypu are allocating. It can be omitted or otherwise sizeof(obj->name)` can be used
  • With %49s I make sure that at most 49 characters + the string terminator are written in my char arrays, avoiding undesirable out of bounds access

As an alternative, you could change the Std definition in order to statically define the size of name and surname char arrays:

typedef struct Std{
    char name[50];
    char surname[50];
    int yearOfBirth;
} Std;

scanf("%49s", obj->name);
scanf("%49s", obj->surname);
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • See [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Where did the OP say they were using a C++ compiler? – lurker Jun 02 '20 at 01:01
  • @lurker they didn't say it. As I have written I know it because they casted to Std the result of calloc in order to remove warning/error. ;) Even out of beginners area this is pretty common (for example... the embedded code of my company's fw) – Roberto Caboni Jun 02 '20 at 01:07
  • @lurker ... anyway I removed the casting and rephrased the description. I keep mentioning the C++ compiler note in case op is actually using it and gets puzzled by the warning/error – Roberto Caboni Jun 02 '20 at 01:13