Reputation:
I know that the below code is not valid since %s
expects an argument of type char *
but I have given an argument of type char **
.
#include <stdio.h>
struct employee
{
int id;
char name[20];
float salary;
};
int main(void)
{
struct employee e;
scanf("%19s", &e.name);//Invalid line
printf("%s", e.name);
}
But I get a different warning:
./ Playground / file0. c: In function main:. / Playground / file0. c: 11: 15: warning: format '% s' expects argument of type' char * ', but argument2 has type char (*) [20]' [- Wformat =] 11 | scanf ("% 195", & e. name); | char (*) [20] char *
I am pretty much sure that char **
and char (*)[20]
are somewhat equivalent but not sure how they are.
char **
: pointer to a pointer to a char.
char (*)[20]
: An array of pointers to a char. — Not sure if I am totally right here.
I am not getting it. How are they equivalent? Please enlighten me.
Upvotes: 1
Views: 5941
Reputation: 225807
The type char (*)[20]
is read as "pointer to array of size 20 of char
. It is not an array of pointers to char
.
An array (of size 20) of pointers to char
would be char *[20]
. Because this is an array, it can decay to a pointer to the first element of the array. Since the array's elements are of type char *
, such a pointer would have type char **
.
Going back to your code, e.name
has type char [20]
, i.e. array of size 20 of char
. From there it follows that &e.name
has type char (*)[20]
, i.e. pointer to array of size 20 of char
.
Upvotes: 1