Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to master the structure of C language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report