STRUCTURE IN C PROGRAMMING and USING TYPEDEF IN STRUCTURE and LINK LIST EXAMPLE

NEED TO REMEMBER

& = address-of operator

* = indirection operator / pointer c program and multiplication in math function

-> = indirect membership operator

 

The struct Keyword

FORMAT:

struct tag {
structure_member(s);
/* additional statements may go here */
} instance;

OR WITHOUT INSTANCE

struct tag {
structure_member(s);
/* additional statements may go here */
};

To use the structure or template, you use the following format:

struct tag instance; //

Example Simple Structures

struct axis {
int x;
int y;
};  // do not forget the semicolon.

how to use that structure add an instance or instances?

struct axis {
int x;
int y;
} first, second; //instance or instances….

OR

struct axis first, second; //initialize using struct keyword
ACCESSING STRUCTURE ELEMENTS OR MEMBERS?
first.x = 10;
first.y = 20;
second.x = 30;
second.y = 40;

OR

first = second;

is equivalent to this statement below:

first.x = second.x;
first.y = second.y;

STRUCTURE THAT CONTAINS STRUCTURE
NOTE: Let us extend the structure axis above.

struct graph { //structure
struct axis topleft; //struct axis previous example
struct axis bottomrt; //struct axis previous example
};

HOW TO USE STRUCTURE THAT CONTAINS ANOTHER STRUCTURE?
CREATE AN INSTANCE IN 2 WAYS.

struct graph { //structure
struct axis topleft; //structure
struct axis bottomrt; //structure
} mygraph; //you add instance here…..do not forget the semicolon otherwise error!!

OR

struct graph mygraph;

HOW TO ACCESS THE MEMBER OR ELEMENTS of STRUCTURE THAT CONTAINS STRUCTURE?

mygraph.topleft.x = 0;
mygraph.topleft.y = 10;
mygraph.bottomrt.x = 100;
mygraph.bottomrt.y = 200;

STRUCTURE THAT CONTAINS AN ARRAY

struct axis {
int x[4]; //four elements of array integer review variable types in c.
int y[4];
};

array of x and y illustration without value:
x[0], x[1], x[2], x[3] //array subscript is 0;
y[0], y[1], y[2], y[3] //array subscript is 0;

HOW TO ACCESS STRUCTURE ELEMENTS OR MEMBERS WITH ARRAYS?

HOW TO USE? TYPE THIS…: struct axis graph;

graph.x[2] = 100;
graph.y[1] = 200;

your array now is:
x[0], x[1], x[2]=100, x[3] //array subscript is 0;
y[0], y[1]=200, y[2], y[3] //array subscript is 0;

NEXT IS ARRAY OF STRUCTURE

struct axis {
int x[4]; //four elements of array integer review variable types in c.
int y[4];
};

HOW TO USE?

struct axis graph[4];

graph[0].x[0]
graph[1].x[1]
graph[2].x[2]
graph[3].x[3]

graph[0].y[0]
graph[1].y[1]
graph[2].y[2]
graph[3].y[3]

If the elements or members of structure is character (char) string or text 255(0xFF IN HEX) see ASCII Code keys of keyboard this is how you use the ARRAY OF STRUCTURE.

struct data {
char fname[20]; //20 letters LAST IS THE NULL “”
char lname[20]; //20 letters LAST IS THE NULL “”
char phone[10]; //10 letters LAST IS THE NULL “”
};

struct data person[4];

person[0].fname = “foo”; //fname
person[0].lname = “bar”; //lname
person[0].phone = “00-012342343”; //telephone number
.
.
.
.
.
.
person[3].fname = “foo3”; //fname
person[3].lname = “bar3”; //lname
person[3].phone = “03-012342343”; //telephone number

PRINTING IN CODE: REMEMBER THE SUBSCRIPT OF ARRAY IS ZERO(0) THAT IS THE REASON i = 0;

for (i = 0; i < 4; i++)
{
printf(“Name: %s %s”, person[i].fname, person[i].lname);
printf(“\t\tPhone: %s\n”, person[i].phone);
}

OUTPUT: foo…foo3, bar…..bar3, phone 0 to 3;

INITIALIZING SIMPLE STRUCTURE MEANING WE PUT VALUE TO STRUCTURE INSTANTLY

struct axis {
int x;
int y;
} graph = {10, 20} ;  // do not forget the semicolon.

so the value of graph.x = 10, and graph.y = 20

ANOTHER EXAMPLE:

struct sale {
char client[20];
char item[20];
float amount;
} mysale = { “Ina Morata”,”Tomatoe”, 1.74 };

INITIALIZING MORE COMPLEX STRUCTURE OR ARRAY OF STRUCTURES

struct client {
char company[20];
char contact[25];
};

struct sale {
struct client buyer; //remember structure within structure example above?
char item[20];
float amount;
};

struct sale y2014[100] =
{
{ { “Fruits ng Ina Mo Inc.”, “Ina Morata”},
“Tomatoe”,
1.00
}, //don’t forget the comma for the next record

{ { “Juice ko Day Inc.”, “Bonga Kaday”},
“Pineapple”,
2.00
}
};

STRUCTURES AND POINTERS

struct data {
int *value;
int *rate;
} rec;

rec.value = &amount; //value is a pointer
rec.rate = &interest; //rate is a pointer

CHAR type of POINTER.

struct message {
char *ptr1;
char *ptr2;
char *ptr3;
} myptrs;

myptrs.ptr1 = “Isaiah 9:6”;
myptrs.ptr2 = “Isaiah 7:14”;
myptrs.ptr3 = “Propehcy fulfilled in Matthew 1:22-23”;

try in your code:

#include <stdio.h>

struct message {
   char *ptr1;
   char *ptr2;
   char *ptr3;
} myptrs;

main() {
myptrs.ptr1 = "Isaiah 9:6";
myptrs.ptr2 = "Isaiah 7:14";
myptrs.ptr3 = "Propehcy fulfilled in Matthew 1:22-23";

puts(myptrs.ptr1);
puts(myptrs.ptr2);
puts(myptrs.ptr3);

return 0;
}

OUTPUT:
Isaiah 9:6
Isaiah 7:14
Propehcy fulfilled in Matthew 1:22-23

POINTERS TO STRUCTURE …. A POINTER TO STRUCTURE YOU ARE GOING TO ASSIGN A POINTER TO THE WHOLE STRUCTURE OF YOUR TEMPLATE.

struct person {
int number;
char name[10];
};

Now declare a pointer to type person

struct person customer;
struct person *p_ptr;

INITIALIZE YOUR POINTER
p_ptr = &customer; //do not forget the AMPERSAND OR

ACCESSING THE ELEMENTS

You have to use (indirect membership operator symbol (->) (a hyphen followed by the greater-than symbol)

p_ptr->number;   // see “->” symbol
p_ptr->name;

or

(*p_ptr).number

or

customer.number
customer.name

EXAMPLE:

#include <stdio.h>

struct person {
  int number;
  char name[10];
};

struct person  customer;
struct person  *p_ptr;

main()
{
p_ptr = &customer;
(*p_ptr).number = 100;

/* printing the same value in different format */
printf("%d\n", (*p_ptr).number);
printf("%d\n",  p_ptr->number);
printf("%d\n", customer.number);
}

TAKENOTE: *p_ptr must be enclosed in parentheses because the (.) operator has a higher precedence than the (*) operator.

POINTERS AND ARRAYS OF STRUCTURE

struct person {
int number;
char name[10];
};

struct person data[100];
struct person *person_ptr;

person_ptr = data;

TAKENOTE: THE NAME ITSELF OF AN ARRAY IS THE POINTER OF THE FIRST ELEMENT OF AN ARRAY.
person_ptr = &data[0];

printf(“%d %s”, person_ptr->number, person_ptr->name);

PASSING STRUCTURES AS ARGUMENTS TO FUNCTIONS

struct entry {
float amount;
char name[30];
} records; /*instanciated already named records */

void print_sales(struct data x);

#include <stdio.h>

/* Structure to hold the data entry. */

struct entry {
   float amount;
   char name[30];
} records;            /*instanciated already named records */

/* The function prototype. The function has no return value because of void, */

void print_sales(struct entry x); //see the structure inside the parenthesis?

 main()
 {

 /* Input the data entry */

 printf("Enter name only: \n");
 scanf("%s", records.name);

 printf("\nEnter the amount paid: ");
 scanf("%f", &records.amount);

 /* Call the print_sales() function. */
 print_sales( records );
   return 0;
 }

 /* the FUNCTION */

 void print_sales(struct entry y)
 {
   printf("\nCustomer %s paid $%.2f.\n", y.name, y.amount);
 }

Enter the name: FOO
Enter the amount pad: 100
OUTPUT: Customer FOO paid $100.00.

SEE HOW THE typedef AFFECTS THE struct

#include <stdio.h>

typedef struct{
   int x;
   int y;
} axis;

main()
{

axis first; 

/* see the declaration above no need to use the word "struct" in instance of the structure.
in previous example we use struct axis first; now no more "struct" */

first.x = 10;
first.y = 11;
printf("%d", first.x);
return 0;
}

OUTPUT: 10

ANOTHER EFFECT OF TYPEDEF IN STRUCTURE

#include <stdlib.h> //i use malloc() = memory allocation
#include <stdio.h>
#include <string.h> //i use strcpy() = string copy

struct data {
 char name[20];
 struct data *next;
};

// LET you to write PERSON in place of "struct data" and NODE in place of struct data *. 

 typedef struct data PERSON; //struct data
 typedef PERSON *NODE; // data pointers

main()
{

 /* Head, new, and current element pointers. */
 NODE head = NULL;
 NODE new = NULL;
 NODE current = NULL;

 //SEE HOW WE USE THOSE ALIASES AND POINTERS?

 new = (NODE)malloc(sizeof(PERSON));
 new->next = head;
 head = new;
 strcpy(new->name, "FOOBAR");

 /* Print all data  */

 current = head;
 while (current != NULL)
 {
   printf("\n%s", current->name);
   current = current->next;
 }
 printf("\n");
 return(0);
}

YOU CAN ADD MORE RECORDS BY CONTROLLING ALL THE POINTERS (THAT IS THE EXAMPLE OF “LINK LIST” IN C PROGRAMMING)
OUTPUT: FOOBAR

ANOTHER EXAMPLE HOW TO USE typedef in structure.

#include <stdio.h>
//BEFORE: WITHOUT TYPEDEF see the "struct Node *nextptr";

/*
struct Node {
    int data;
    struct Node *nextptr;
};
*/

//AFTER: with typedef keyword

typedef struct Node Node;

struct Node {
    int data;
    Node *nextptr;
};

struct Node *start, *end, *current, *previous, *marker;

typedef struct Node *NodePtr;

/* have you notice all the pointers below no (*) */

NodePtr  start, end, current, previous, marker;

main(){

    printf("Review all the codes above about Using typedef with pointers");

return 0;
}

/* LINK LIST EXAMPLE USING THE POINTERS AND STRUCT */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct data {
  char name[100];
  struct data *next; //head, first element or top pointer
};

typedef struct data PERSON; //typedef given struct data a new name (PERSON);
// ANOTHER DECLARATION STYLE: struct data *head, *new, *current, *current2;
// typedef PERSON *LINK; // this is the POINTER(*) to struct data

main()
{

 PERSON *head = NULL; // first element
 PERSON *new = NULL; //new element
 PERSON *current = NULL; //current element
 PERSON *current2 = NULL; //additional pointer marker for deletion

 /* you can use these declaration in above pointers
    using "typedef PERSON *LINK;" below
 */

 /*
 LINK head = NULL;
 LINK new = NULL;
 LINK current = NULL;
 LINK current2 = NULL

 // you can declare above statement like this:

 struct data *new;
 struct data *head;
 struct data *current;
 struct data *current2;

 also you can change all malloc declaration like this:
 new = (LINK)malloc(sizeof(PERSON));

 */

 /*adding: first element*/
 new = (PERSON*)malloc(sizeof(PERSON));
 new->next = head;
 head = new;
 strcpy(new->name, "1st");

 /* last record */
 current = head;
 while (current->next != NULL)
 {
   current = current->next;
 }

 new = (PERSON*)malloc(sizeof(PERSON));
 current->next = new;
 new->next = NULL;
 strcpy(new->name, "Last Record");

 /* adding new element at the second position in the list */

 new = (PERSON*)malloc(sizeof(PERSON));
 new->next = head->next;
 head->next = new;
 strcpy(new->name, "next to head record");

/* DELETING IN THIS AREA REMOVE COMMENTS ONE BY ONE YOU CAN SEE THE EFFECTS OF DELETE COMMANDS */

 /*DELETING THE FIRST RECORD*/

  //head = head->next; //enable this one by one

/*deleting the last record in the list*/
/*
  current = head;
  current2 = current->next;
  while (current2->next != NULL)
  {
    current = current2;
    current2 = current->next;
  }
    current->next = NULL;
    if(head == current)
       head = NULL;
*/

 /*delete an elements within the list*/
   current2 = current->next;
   current->next = current2->next;

/* END OF ENABLE AREAS TESTING THE MEMBER OF THE LIST*/

 /*Print All records*/
 current = head;
 while (current != NULL)
 {
   printf("%s\n", current->name);
   current = current->next;
 }

 return 0;
}

OUTPUT:
1st
Last Record

I deleted the middle records…try it!! Try to enable some comments in DELETING AREAS OF THE CODE.

THE BELOW CODES ARE SINGLE LINK LIST “WITHOUT” USING TYPEDEF.

 


#include <stdlib.h>;
#include <stdio.h>;
#include <string.h>;

struct person {
char name[20];
struct person *next;
};

main()
{

struct person *head;
struct person *new;
struct person *current;

head = NULL;

/* ADDING THE FIRST RECORD */
new = (struct person*)malloc(sizeof(struct person));
new->next = head;
head = new;
strcpy(new->name, "FIRST RECORD");

/* ADDING RECORD TO THE 'END" OF THE LIST TO BECOME THE LAST RECORD */
/* NOTE: end of the list the new->;next should be NULL */

current = head;
while (current->next != NULL)
current = current->next;

new = (struct person*)malloc(sizeof(struct person));
current->next = new;
new->next = NULL;
strcpy(new->name, "LAST RECORD");

/* ADDING ELEMENT TO THE MIDDLE OF THE LIST */

new = (struct person*)malloc(sizeof(struct person));
new->next = head->next;
head->next = new;
strcpy(new->name, "MIDDLE RECORD");

/* print  all records */

current = head;
while (current != NULL)
{
printf("%s\n", current->name);
current = current->next;
}

//printf("%d", sizeof(struct person*)); //4
//printf("%d", sizeof(struct person)); //24
return 0;
}

OUTPUT:
FIRST RECORD
MIDDLE RECORD
LAST RECORD

Advertisements
This entry was posted in C. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s