请考虑我写的以下代码:
#include <stdio.h>
typedef struct driver{
char name[20];
int dno;
char rout[20];
int expe;
}drive;
int main()
{
drive d[3];
for (int i = 0; i < 3; i++)
{
printf("Enter your name:");
scanf("%s", d[i].name);
printf("Enter your rout:");
scanf("%s", d[i].rout);
printf("Enter your driving licence number:");
scanf("%d", &d[i].dno);
printf("Enter your Exprinc in km:");
scanf("%d", &d[i].expe);
}
for (int i = 0; i < 3; i++)
{
printf("***************************************************************\n");
printf("Name of driver %d is %s \n", i+1, **d[i].name);**
printf("Rout of driver %d is %s \n", i+1, **d[i].rout);**
printf("driving licence number of driver %d is %d \n", i+1, d[i].dno);
printf("exprence of driver %d in km is %d \n", i+1, d[i].expe);
printf("***************************************************************\n");
}
return 0;
}
为什么我在这里无法使用 &
?它发出这样的警告:
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat=]
15 | scanf("%s", &d[i].name);
| ~^ ~~~~~~~~~~
| | |
| | char (*)[20]
| char *
travel_agency.c:17:17: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat=]
17 | scanf("%s", &d[i].rout);
| ~^ ~~~~~~~~~~
| | |
| | char (*)[20]
| char *
答案 0 :(得分:3)
根据定义,d[i].name
与 &(d[i].name[0])
相同,因为在 C 中,在许多情况下,数组衰减为指向其第一个元素(索引为 0)的指针。
有关详细信息,请参阅 Modern C、this C reference 和一些最新的 C 标准,例如 n1570 或更新的内容,例如 n2310
考虑在 C 源代码中使用 Frama-C 或 Clang static analyzer。
请注意 scanf(3) 可能会失败。您应该使用返回的扫描项目计数进行测试。所以代码
printf("Enter your name:");
if (scanf("%s", d[i].name)<1)
perror("scanf name");
在某些情况下,printf(3) 也可能失败。
通过研究一些现有的 free software 的源代码获得灵感,例如 GNU make 或 GNU bison。两者都可能对您有用。