How to use structure pointer

Pointer for structure

The following code shows how to use the structure member and structure pointer operators.


#include <stdio.h>
//from ww  w.  ja  v  a  2s.  c  om
struct card {                           
   char *face; 
   char *suit; 
};

int main()
{ 
   struct card aCard; 
   struct card *cardPtr;

   aCard.face = "Ace";   
   aCard.suit = "Spades";

   cardPtr = &aCard;

   printf( "%s%s%s\n%s%s%s\n%s%s%s\n", aCard.face, " of ", aCard.suit,
      cardPtr->face, " of ", cardPtr->suit,                           
      ( *cardPtr ).face, " of ", ( *cardPtr ).suit );                 
   
   return 0;
}

The code above generates the following result.


Ace of Spades
Ace of Spades
Ace of Spades

Allocate memory for structure


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//from w  ww  .j  a va 2 s. c  o m
struct address {
  char name[400];
  char street[400];
  char city[400];
  char state[30];
  char zip[100];
};

int main()
{
  struct address *p;

  if((p = malloc(sizeof(struct address)))==NULL) {
    printf("Allocation Error\n");
    exit(1);
  }
  return p;
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing