Reputation: 1
Please consider following code I wrote:
#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;
}
Why I am unable to use &
here? It gives warning like this:
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 *
Upvotes: 0
Views: 92
Reputation: 1
By definition, d[i].name
is the same as &(d[i].name[0])
since in C, in many cases, an array decays into the pointer to its first element (of index 0).
For details, see Modern C, see this C reference, and some recent C standard, such as n1570 or something newer such as n2310
Consider using Frama-C or the Clang static analyzer on your C source code.
Notice that scanf(3) can fail. You should test that, using the returned scanned item count. So code
printf("Enter your name:");
if (scanf("%s", d[i].name)<1)
perror("scanf name");
and in some cases, printf(3) could also fail.
Take inspiration by studying the source code of some existing free software, such as GNU make or GNU bison. Both might be useful to you.
Upvotes: 3