Search
 
SCRIPT & CODE EXAMPLE
 

C

c assign pointer to struct


// setting a pointer to a struct in C
// and set value by pointer
#include <stdio.h>
#include <stdbool.h>

// a struct called airplane
typedef struct
{
    int fuel;
    double speed;
    bool landing_gear_down;
} airplane;

int main()
{
    // make a pointer
    airplane *Hummingbird; // *Hummingbird is now a pointer and it can be assigned to point at a struct of type airplane.

    // this creates a struct of type airplane and assigns it a name of cessna and initializes it
    airplane cessna = {50, 155, true};

    Hummingbird = &cessna; // now assign the pointer to the struct address

    // you can now call data types / variables via the pointer
    (*Hummingbird).fuel; // this is a little messy
    Hummingbird->speed;  // this is clean and understandable

    printf("
the cessna has %d liters of fuel", Hummingbird->fuel);

    // set the value by pointer

    Hummingbird->fuel = 15;

    printf("
the cessna has %d liters of fuel", Hummingbird->fuel);

    (*Hummingbird).landing_gear_down = false;
   // or 
  	Hummingbird->landing_gear_down = false;

    if (Hummingbird->landing_gear_down == false)
    {

        printf("
landing gear is up");
    }
    else
    {

        printf("
landing gear is down");
    }
};
Comment

return pointer to struct in C

typedef struct {
  char name[20];
  int age;
} Info;

Info* GetData() {
  Info *info;

  info = (Info *) malloc( sizeof(Info) );
  scanf("%s", info.name);
  scanf("%d", &info.age);

  return info;
}
Comment

C Pointers to struct

struct name {
    member1;
    member2;
    .
    .
};

int main()
{
    struct name *ptr, Harry;
}
Comment

PREVIOUS NEXT
Code Example
C :: how to print the first character of a string in c 
C :: read from a file c 
C :: how to print value of pointer in c 
C :: check prime number or not c 
C :: scanf string in c 
C :: malloc in c 
C :: fractional knapsack problem in c 
C :: what is system function in c 
C :: how make a character in c scanf 
C :: goto statement in c 
C :: Counting Sort C 
C :: C Program to Find Largest and Smallest Number among N 
C :: c in array 
C :: c fopen 
C :: fgets remove newline 
C :: star pattern in c 
C :: bootstrap form 
C :: latex remove page number from footer 
C :: c convert string to size_t 
C :: converting strings to numbers in c 
C :: class in oops 
C :: include ‘<stdlib.h’ or provide a declaration of ‘exit’ 
C :: delay in c programming for linux 
C :: yum install supervisor amazon linux 
C :: define constant c 
C :: majuscule en c 
C :: man strstr 
C :: C Accessing Union Members 
C :: parcel-builder put image in sub folder 
C :: fork 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =