Water drop stone wearing C language Typedef problem

xiaoxiao2021-03-06  18

Basic explanation

Typedef is a keyword for the C language. The role is to define a new name for a data type. The data type here includes internal data types (INT, CHAR, etc.) and custom data types (Struct, etc.).

There are generally two in programming using TypeDef, one is a new name that is easy to remember to the variable, and the other is to simplify some complicated type declarations.

As for TypedEf, what is subtle, please follow the specific elaboration of several problems.

2. Typedef & structure problem

When defining a structure with the following code, the compiler reports an error, why? Does the C language not allowed to include their own pointers in the structure? Please guess first, then see the description:

Typedef struct tagnode {char * pitem; pnode pnext;} * pnode;

Answer and analysis:

1, the simplest use of Typedef

TYPEDEF Long Byte_4;

Give a new name for the known data type LONG, called byte_4.

2, TypedEf and structural combination

TYPEDEF STRUCT TAGMYSTRUCT {Int inum;} mystruct;

This statement actually completes two operations:

1) Define a new structure type

Struct tagmystruct {int inum; long LLEngth;

Analysis: tagmystruct is called "tag", "tag", actually a temporary name, struct keyword, and tagmystruct together, constitute this structural type, whether there is typedef, this structure exists.

We can use Struct Tagmystruct VarName to define variables, but pay attention to define variables using tagmystruct varname, because Struct and Tagmystruct are combined to represent a structural type.

2) Typedef has a name for this new structure called mystruct.

Typedef struct tagmystruct mystruct;

Therefore, MyStruct is actually equivalent to Struct Tagmystruct, we can use MyStruct VarName to define variables.

Answer and analysis

The C language certainly allows the structure to include its own pointer, we can see countless examples in the implementation of data structures such as the chain list, the fundamental problem of the above code is the application of TypeDef.

According to our above, you can know that in the process of the new structure, I encountered a statement of the PNEXT domain. The type is pnode. To know that PNODE is a new name, then the type itself has not been completed, this type The new name is still not existed, which means that the compiler does not know PNODE at all.

There are many ways to solve this problem:

1),

Typedef struct tagnode {char * pitem; struct tagnode * pnext;} * pnode;

2),

Typedef struct tagnode * pnode; struct tagnode {char * pitem; pNode pnext;

Note: In this example, you use TypeDef to give a new name that is not fully declared. The C language compiler supports this approach.

3), standardized approach:

Struct tagnode {char * pitem; struct tagnode * pnext;}; type;

转载请注明原文地址:https://www.9cbs.com/read-42711.html

New Post(0)