#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char Name[100];
typedef struct Daughter
{
Name name;
int age;
int height;
}Tochter;
typedef struct Father
{
Tochter kleine[6];
Name v;
int age;
int height;
int numofdaugh;
}Dad;
int main (void)
{
Vater Martin, *pDad;
int numofdau;
printf("How many Daughters? ");
scanf("%i", Martin.numofdaugh);
pDad = &Martin;
pDad->kleine[0].name = "Alice";
// I also tried Martin.kleine[0].name = "Alice";
}
I also tried to change elements with functions but it still didnt work and the error msg is: "expression must have pointer-to-object type but it has type "Tochter".
CodePudding user response:
- you cant assign arrays.
- scanf requires pointer,.
scanf("%i", &Martin.numofdaugh);
pDad = &Martin;
strcpy(pDad->kleine[0].name, "Alice");
PS Type Dad
should be Vater
CodePudding user response:
scanf
needs to be passed a pointer.
Rather than:
scanf("%i", Martin.numofdaugh);
Pass a pointer to Martin.numofdaugh
:
scanf("%i", &Martin.numofdaugh);
You also want to use strncpy
to copy a string into a Name
.
Name bobs_name = {0};
strncpy(bobs_name, "Bob", 100);
Using strncpy
rather than strcpy
prevents the possibility of an overflow, as a Name
is limited to 100 characters.
CodePudding user response:
pDad->kleine[0].name = "Alice";
is wrong because you can't copy C-strings this way (use strcpy
).
More correct is:
strcpy(pDad->kleine[0].name,"Alice");
CodePudding user response:
@Chris answer is correct, but you also have a Type Vater
that does not exist elsewhere.