简体   繁体   English

C 中的 char (*)[20] 是什么意思?

[英]What does char (*)[20] in C mean?

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 ** .我知道下面的代码无效,因为%s需要一个char *类型的参数,但我给出了一个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 **char (*)[20]在某种程度上是等价的,但不确定它们是怎样的。

char ** : pointer to a pointer to a char. char ** : 指向 char 的指针。

char (*)[20] : An array of pointers to a char. char (*)[20] :指向 char 的指针数组。 — Not sure if I am totally right here. — 不确定我是否完全正确。

I am not getting it.我不明白。 How are they equivalent?它们如何等效? Please enlighten me.请赐教。

The type char (*)[20] is read as "pointer to array of size 20 of char . It is not an array of pointers to char . char (*)[20]类型被读作“指向char大小为 20 的数组的指针。它不是指向char的指针数组。

An array (of size 20) of pointers to char would be char *[20] .指向char的指针数组(大小为 20)将是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 ** .由于数组的元素是char *类型,因此这样的指针将具有char **类型。

Going back to your code, e.name has type char [20] , ie array of size 20 of char .回到您的代码, e.name的类型为char [20] ,即char大小为 20 的数组。 From there it follows that &e.name has type char (*)[20] , ie pointer to array of size 20 of char .从那里可以看出&e.name的类型为char (*)[20] ,即指向char大小为 20 的数组的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM