简体   繁体   中英

Pointer at declaration of “typedef struct”

Could somebody please explain to beginner "C" programmer what is *sometext ? How can i use it? First sometext is name of structure as i undestand.

typedef struct
{
   ULONG x;
   ULONG y;
} SOMETEXT, *SOMETEXT;

It's equivalent to:

struct unnamed_type_that_im_giving_a_name_to_here {
   ULONG x;
   ULONG y;
};

struct unnamed_type_that_im_giving_a_name_to_here SOMETEXT;
struct unnamed_type_that_im_giving_a_name_to_here *SOMETEXT;

Note that this is invalid code since you're delcaring SOMETEXT twice. But I'm assuming that in your actual code those are different names.

Using one typedef you can introduce several aliases for types.

Here is a simple demonstrative program

#include <stdio.h>

typedef int INT_TYPE, *INT_PTR;

int main(void) 
{
    INT_TYPE x = 10;
    INT_PTR p = &x;

    printf( "x = %d\n", *p );

    return 0;
}

Its output is

x = 10

Here in the program the typedef introduces two aliases: INT_TYPE for the type int and INT_PTR for the type int * .

As for your example of a typedef then for starters it is invalid becuase the same identifier SOMETEXT is used to declare two different types in the scope.

However if to rename the second identifier as for example SOMETEXT_PTR then this typedef

typedef struct
{
   ULONG x;
   ULONG y;
} SOMETEXT, *SOMETEXT_PTR;

you can imagine like two separate typedefs

typedef struct
{
   ULONG x;
   ULONG y;
} SOMETEXT;

typedef SOMETEXT *SOMETEXT_PTR;

That is SOMETEXT is an alias for an unnamed structure and SOMETEXT_PTR is an alias for the type pointer to the unnamed structure.

I see below:-

typedef struct SOMETEXT
{
   ULONG x;
   ULONG y;
};

Here we have declared a struct (structure) which name is SOMETEXT and that is why this kind of declaration is call user define type.

So now we are using the name of the struct like below:-

  struct SOMETEXT  *s, *p, *q;

So in the above code we have declared 3 pointer of type SOMETEXT. And if you noticed every time we are using struct in front of name SOMETEXT . To avoid that we will provide a alias to SOMETEXT like below:-

  typedef struct SOMETEXT1
  {
    ULONG x;
    ULONG y;
  } *SOMETEXT;

so now we can declare pointer of SOMETEXT like below:-

  SOMETEXT s, p, q;

Here we don't need to use * in front of each variable. This is same as previous declaration of struct SOMETEXT *s, *p, *q;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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