1 / 5

Understanding Structures and Pointers in C Programming

This guide explores the fundamentals of structures and pointers in C programming. It covers how to define structures, access structure members, and manage memory allocation. Key examples illustrate the use of the `offsetof` macro to determine the offsets of structure members. Additionally, you'll find detailed syntax for working with structures and pointers, including dynamic memory allocation using `malloc`. Learn how to define custom data types with `typedef` and efficiently manage data in your C applications.

fritz
Télécharger la présentation

Understanding Structures and Pointers in C Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };

  2. Structs and pointers struct S { inta; char* b; } myS; // pointer to a struct struct S * sp; // pointer to a struct data member Determine the address of a or b

  3. Pointers and struct data members • offsetof(<type>,<member>) • Gives the offset of a variable within a structure (function in stddef.h) struct S { int a; char* b; } myS; char* pb = (char*)&myS + offsetof(struct S, b);

  4. Struct and pointer syntax example #include<stdio.h> typedefstruct{ char *name; intnumber; } TELEPHONE; intmain(){ TELEPHONE index; TELEPHONE *ptr_myindex; ptr_myindex= &index; ptr_myindex->name = "Jane Doe"; ptr_myindex->number = 12345; printf("Name: %s\n", ptr_myindex->name); printf("Telephone number: %d\n", ptr_myindex->number); return 0; }

  5. Another Struct and pointer syntax example (also with allocation) #include<stdio.h> typedefstruct { inti; float PI; char A; } RECORD; int main() { RECORD *ptr_one; ptr_one= (RECORD *) malloc (sizeof(RECORD)); (*ptr_one).i = 10; (*ptr_one).PI = 3.14; (*ptr_one).A = 'a'; printf("First value: %d\n",(*ptr_one).i); printf("Second value: %f\n", (*ptr_one).PI); printf("Third value: %c\n", (*ptr_one).A); free(ptr_one); return 0; } Note: if the struct contains a pointer you may have to allocate memory for that with a second malloc call

More Related