当扫描尝试访问 titolo[i]->nome 时出现错误,我不明白为什么
typedef struct tit *TITOLO;
struct tit {
char nome[20];
};
int main()
{
TITOLO *titolo;
titolo =(TITOLO *) malloc(4*sizeof (TITOLO));
if (titolo == NULL) exit(1);
int i;
for (i=0;i<4;i++) {
printf("Insert title: ");
scanf("%s", titolo[i]->nome);
}
return 0;
}
typedef struct tit *TITOLO;
将 TITOLO 定义为指针类型,而不是结构类型。摆脱它并键入结构:
typedef struct {
char nome[20];
} TITOLO;
TITOLO* titolo = malloc(4*sizeof(*titolo));
你可能想要这个:
typedef struct tit *TITOLO;
struct tit {
char nome[20];
};
int main()
{
TITOLO titolo;
titolo = (TITOLO)malloc(4 * sizeof(struct tit));
if (titolo == NULL) exit(1);
int i;
for (i = 0; i < 4; i++) {
printf("Insert title: ");
scanf("%s", titolo[i].nome);
}
return 0;
}
TITOLO
已经是指针类型。
但最好的做法是按照Lundin的回答和倍增的赞成评论的建议去做:不要将指针类型隐藏在typedefs后面,它只会增加混乱。
顺便说一句:
... = (TITOLO)malloc(...
可以写成:
... = malloc(...
演员阵容根本不必要。