Follow the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Person
{
char name[256];
//char *name;
} person;
typedef struct Population
{
person p;
int num;
struct Population *next;
}people;
void insere_person(person *p){
printf("insira um nome: ");
scanf(" %s", p->name);
}
void insere_people(people *ps){
printf("insira um nome: ");
scanf(" %s", ps->p.name);
printf("insira um numero: ");
scanf(" %d", &ps->num);
}
void insere_person_to_people(person *p, people *ps){
insere_person(p);
printf("insira um numero: ");
scanf(" %d", &ps->num);
ps->p = *p;
}
short vazia(people *ps){
if(ps->next == NULL){ return 1; }
else{ return 0; }
}
void insere_teste(people *ps){
//char nome[256];
people *new_ps = (people *)malloc(sizeof(people));
printf("digite um nome:");
scanf(" %s", ps->p.name);
//scanf(" %s", nome);
new_ps->p = ps->p;
new_ps->next = NULL;
if(vazia(ps)){
ps->next = new_ps;
}
else{
people *tmp = ps->next;
while(tmp->next != NULL){
tmp = tmp->next;
}
tmp->next = new_ps;
}
}
void person_to_string(person *p){
printf("person{nome:%s}\n", p->name);
}
void people_to_string(people *ps){
printf("people{nome:%s, num:%d}\n", ps->p.name, ps->num);
}
void all_to_string(people *ps){
if(vazia(ps)){
printf("ninguem!\n");
return;
}
else{
people *tmp = ps->next;
while(tmp != NULL){
people_to_string(tmp);
tmp = tmp->next;
}
}
}
void menu(person *p, people *ps){
int op = -1;
while(op != 0){
printf("0 - sair\
\n1 - insere pessoa\
\n2 - insere populacao\
\n3 - mostra pessoa\
\n4 - mostra populacao\
\nopcao: ");
scanf(" %d", &op);
switch(op){
case 0:
break;
case 1:
insere_person(p);
break;
case 2:
//insere_people(ps); // funciona
//insere_person_to_people(p, ps); // funciona
insere_teste(ps); // não funciona
break;
case 3:
person_to_string(p);
break;
case 4:
//people_to_string(ps);
all_to_string(ps);
break;
default:
printf("Opcao invalida.\n");
break;
}
}
}
int main()
{
person p;
people ps;
menu(&p, &ps);
return 0;
}
So after testing several ways to insert the data I noticed that in the method "insert_test ()" it of the error in the line:
scanf(" %s", ps->p.name);
I would like someone to explain this error to me, because how to solve it I already know, but it does not help me to know how to solve without understanding what happens.
Another point I would like to learn is because they are all being modified together, I know it is a pointer that is pointing to the same address, but I would like a more didactic explanation for this, because in practice I already learned.
Thank you in advance.