Get the App
SLTechnology News&Howtos  ›  Development  › 

How to master the structure of C language

Shulou Source: shulou.com Published: 2022-06-01 01:35:47 09月21日 Update

This article mainly introduces the C language structure how to master the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe everyone read this C language structure how to master the article will have some gains, let's take a look at it.

Examples:

#include //On 32-bit systems, structs are aligned with four bytes by default when alignment is not specified typedef struct __ST{ int id ; //4 char *name ; //4 float math ; //4}ST;int main(){ ST st ; //Gets the first address of the first element of the struct int *ptr_0 = (int *)(&st); printf ("st: %p ptr: %p \n",&st,ptr_0); //assign *ptr_0 = 100 to the first element of the struct; printf ("*ptr_0 = %d\n",*ptr_0); //Get the first address of the second element of the struct, because the second element is a first-level pointer, you need a second-level pointer to connect char **ptr_1 = (char **)((int)&st+4) ; printf ("ptr_1:%p\n", ptr_1); //assign *ptr_1 = "hello world" to the second element of the struct; printf ("ptr_1:%s\n",*ptr_1); //Get the first address of the third element of the structure, calculate the address of the third element according to the alignment offset float *ptr_2 = (float *)((int)&st+8) ; printf ("ptr_2:%p \n", ptr_2); //assigns a value to the third element of the struct *ptr_2 = 96.78 ; printf("ptr_2:%.2f \n",*ptr_2); //prints the values of all members of the struct printf(" st.id = %d st.name = %s st.math = %.2f\n",st.id,st.name,st.math); return 0;}

Isn't the offset calculated according to the alignment principle here actually the principle of offsetof macro?

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) About "How to master C language structure" The content of this article is introduced here, thank you for reading! I believe everyone has a certain understanding of "how to master C language structure" knowledge. If you still want to learn more knowledge, please pay attention to industry information channel.

Tags: Structure element language address three knowledge content principle pointer article offset value example principle byte namely member easy to operate article time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft vpn MySQL Xiaomi Linux