简体   繁体   English

typedef结构作为指针?

[英]typedef struct as pointer?

I have a question in regards to typedef struct 's that I believe I know the answer to but would like some clarification. 关于typedef struct,我有一个问题,我相信我知道答案,但需要澄清。

Lets say I have: 可以说我有:

typedef struct Scanner{
    //information
}myScanner;

Would that have the same meaning as: 其含义是否与:

typedef struct Scanner *myScanner; 
struct Scanner {
    //information
};

It will be easy to see the difference if you use the same format for both typedef definitions: 如果您对两个typedef定义使用相同的格式,则很容易看出差异:

typedef struct Scanner myScanner;

versus

typedef struct Scanner *myScanner;

Defining a type-alias using typedef is very similar do declaring variables. 使用typedef定义类型别名与声明变量非常相似。 For typedef the asterisk means "define as pointer", just like it does for variables. 对于typedef ,星号表示“定义为指针”,就像对变量一样。

The type definitions are usually in a header file where no vars are created. 类型定义通常在没有创建变量的头文件中。 In your main(), you are supposed to use this type to create vars. 在main()中,应该使用此类型创建var。 In our example, the newly minted type is 'Scanner'. 在我们的示例中,新创建的类型是“扫描仪”。


#include <stdio.h>
#include <stdlib.h>

struct _scanner
{       // example
    int a;
    double b;
    char c;
};
typedef struct _scanner Scanner;


int main()
{
    Scanner s;
    s.a = 10;
    s.b = 3.14;
    s.c = 'N';
    // -------------------
    // If you want to have a
    //  pointer p to scanner, then

    Scanner* p = &s;

    p->a = 20;
    p->b = 2.72;
    p->c = 'Y';

    printf("%d, %.2lf, %c\n",
           s.a, s.b, s.c);

    return EXIT_SUCCESS;
}

Output: 输出:

20, 2.72, Y

Once the variable is created, you can make a pointer to it, as a pointer must be able to point to something. 创建变量后,您可以创建指向它的指针,因为指针必须能够指向某物。 The output shows that values have been successfully manipulated. 输出显示值已被成功操纵。

typedef struct Scanner *myScanner; — here you are declaring type pointer to a struct Scanner . —在这里,您要声明指向struct Scanner类型指针。

typedef struct Scanner myScanner; — is a declaration of a new type. —是新类型的声明。

What this means is, in the first case, you define a pointer to struct Scanner , for arithmetic calculations etc, the type of element that is pointed to. 在第一种情况下,这意味着要定义一个指向struct Scanner的指针,以进行算术计算等所指向的元素的类型。 The size of myScanner will equal size of void* (pointer size on your os). myScanner的大小将等于void*大小(操作系统上的指针大小)。

For the second case, you are defining a new type of element; 对于第二种情况,您正在定义一种新的元素类型; it's size is 它的大小是
sizeof(struct Scanner) == size of(myScanner) . sizeof(struct Scanner) == size of(myScanner)

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

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