Incomplete structs
This presentation is the property of its rightful owner.
Sponsored Links
1 / 5

Incomplete Structs PowerPoint PPT Presentation


  • 51 Views
  • Uploaded on
  • Presentation posted in: General

Incomplete Structs. struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };. Structs and pointers. struct S { int a ; char * b ; } myS ; // pointer to a struct struct S * sp ;

Download Presentation

Incomplete Structs

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Incomplete structs

Incomplete Structs

struct B;

struct A {

struct B * partner;

// other declarations…

};

struct B {

struct A * partner;

// other declarations…

};


Structs and pointers

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


Pointers and struct data members

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);


Incomplete structs

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;

}


Incomplete structs

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


  • Login