Close
Close

Structure in C


We have already dealt with arrays. Arrays are used to store similar type of data. Have you ever thought if there is any way to store dissimilar data?

Answer is yes. We use structures to store data of different types. For example, you are a student. Your name is a string and your phone number and roll_no are integers. So, here name, address and phone number are those different types of data. Here, structure comes in picture.

Defining a Structure

The syntax for structure is:

struct structure_name
{
  data-type member-1;
  data-type member-2;
  data-type member-3;
  data-type member-4;
};

In our case, let's name the structure as 'student'. The members of the structure in our case are name, roll_no and phone_number.

So, our structure will look like:

struct student
{
  int roll_no;
  char name[30];
  int phone_number;
};

Declaration of Structure Variable


Just as we declare variables of type int, char etc, we can declare variables of structure as well.

Suppose, we want to store the roll no., name and phone number of three students. For this, we will define a structure of name 'student' (as declared above) and then declare three variables, say 'p1', 'p2' and 'p3' (which will represent the three students respectively) of the structure 'student'.

struct student
{
  int roll_no;
  char name[30];
  int phone_number;
};
main()
{
  struct student p1, p2, p3;
}

Here, p1, p2 and p3 are the variables of the structure 'student'.

We can also declare structure variables at the time of defining structure as follows.

struct student
{
  int roll_no;
  char name[30];
  int phone_number;
}p1, p2, p3;

Now, let's see how to enter the details of each student i.e. roll_no, name and phone number.

Suppose, we want to assign a roll number to the first student. For that, we need to access the roll number of the first student. We do this by writing

p1.roll_no = 1;

This means that use dot (.) to use variables in a structure. p1.roll_no can be understood as roll_no of p1.

If we want to assign any string value to a variable, we will use strcpy as follows.

strcpy(p1.name, "Brown");

Now let's store the details of all the three students.

#include <stdio.h>
#include <string.h>
int main()
{
  struct student
  {
    int roll_no;
    char name[30];
    int phone_number;
  };
  struct student p1 = {1,"Brown",123443};
  struct student p2, p3;
  p2.roll_no = 2;
  strcpy(p2.name,"Sam");
  p2.phone_number = 1234567822;
  p3.roll_no = 3;
  strcpy(p3.name,"Addy");
  p3.phone_number = 1234567844;
  printf("First Student\n");
  printf("roll_no : %d\n", p1.roll_no);
  printf("name : %s\n", p1.name);
  printf("phone_number : %d\n", p1.phone_number);
  printf("Second Student\n");
  printf("roll_no : %d\n", p2.roll_no);
  printf("name : %s\n", p2.name);
  printf("phone_number : %d\n", p2.phone_number);
  printf("Third Student\n");
  printf("roll_no : %d\n", p3.roll_no);
  printf("name : %s\n", p3.name);
  printf("phone_number : %d\n", p3.phone_number);
  return 0;
}
Output
First Student
roll_no : 1
name : Brown
phone_number : 123443
Second Student
roll_no : 2
name : Sam
phone_number : 1234567822
Third Student
roll_no : 3
name : Addy
phone_number : 1234567844
Always use strcpy to assign a string value to a string variable.

The reason for this is that in C, we cannot equate two strings (i.e. character arrays). If we had written ' p1.name="Brown"; ', that would have given an error. Therefore, by writing strcpy(p1,"Brown"), we are copying the string 'Brown' to the string variable p1.name.

struct student p1 = {1,"Brown",123443}; → This is also one of the ways in which we can initialize a structure. In next line, we are just giving values to the variables and printing it.

Structures use continuous memory locations.

Array of Structures


We can also make array of structures. In the first example in structures, we stored the data of 3 students. Now suppose we need to store the data of 100 such children. Declaring 100 separate variables of structure is definitely not a good option. For that, we need to create an array of structures.

Let's see an example for 5 students.

#include <stdio.h>
struct student
{
  int roll_no;
  char name[30];
  int phone_number;
};
int main()
{
  struct student stud[5];
  int i;
  for(i=0; i<4; i++)
    {
      printf("Student %d\n",i+1);
      printf("Enter roll no. :\n");
      scanf("%d", &stud[i].roll_no);
      printf("Enter name :\n");
      scanf("%s",stud[i].name);
      printf("Enter phone number :\n");
      scanf("%d", &stud[i].phone_number);
    }
  for(i=0; i<4; i++)
    {
      printf("Student %d\n",i+1);
      printf("Roll no. : %d\n", stud[i].roll_no);
      printf("Name : %s\n", stud[i].name);
      printf("Phone no. : %d\n", stud[i].phone_number);
    }
  return 0;
}
Output
Student 1
Enter roll no. :
1
Enter name :
sam
Enter phone number :
1321
Student 2
Enter roll no. :
2
Enter name :
brown
Enter phone number :
4321
Student 3
Enter roll no. :
3
Enter name :
addy
Enter phone number :
4543
Student 4
Enter roll no. :
4
Enter name :
max
Enter phone number :
3412
Student 1
Roll no. : 1
Name : sam
Phone no. : 1321
Student 2
Roll no. : 2
Name : brown
Phone no. : 4321
Student 3
Roll no. : 3
Name : addy
Phone no. : 4543
Student 4
Roll no. : 4
Name : max
Phone no. : 3412

Here, stud[0] stores the information of first student, stud[1] for the second and so on.

We can also copy two structures at one go.

#include <stdio.h>
#include <string.h>
int main()
{
  struct student
  {
    int roll_no;
    char name[30];
    int phone_number;
  };
  struct student p1 = {1,"Brown",123443};
  struct student p2;
  p2 = p1;
  printf("roll_no : %d\n", p2.roll_no);
  printf("name : %s\n", p2.name);
  printf("phone_number : %d\n", p2.phone_number);
  return 0;
}
Output
roll_no : 1
name : Brown
phone_number : 123443

We just wrote p2 = p1 and that's it. All the elements of p1 got copied to p2.

Pointers to Structures


Like we have pointers for int, char and other data-types, we also have pointers pointing to structures. These pointers are called structure pointers.

Now, how to define a pointer to a structure? The answer’s below:

struct structure_name
{
  data-type member-1;
  data-type member-1;
  data-type member-1;
  data-type member-1;
};
main()
{
  struct structure_name *ptr
}

Let's consider an example using structure pointer.

#include <stdio.h>
int main()
{
  struct student
  {
    char name[30];
    int roll_no;
  };
  struct student stud = {"sam",1};
  struct student *ptr;
  ptr = &stud;

  printf("%s %d\n",stud.name,stud.roll_no);
  printf("%s %d\n",ptr->name,ptr->roll_no);

  return 0;
}
Output
sam 1
sam 1

struct stud *ptr; → We have declared that 'ptr' is a pointer of a structure 'student'.

ptr = &stud; → We are making our pointer 'ptr' to point to structure 'stud'.

This was the same thing that we have done earlier up till here. Now, coming to printf.

printf("%s %d\n",ptr->name,ptr->roll_no); → Yes, we use -> to access a structure from its pointer. It is same as we were using (.) with structure, we use -> with pointer.

Passing Structure to Function

We can also pass structure to a function.

There are two methods by which we can pass structures to functions.

  • Passing by Value
  • Passing by Reference

Passing by Value


In this, we pass structure variable as an argument to a function. This will become clear by an example.

#include <stdio.h>
#include <string.h>
struct student
{
  int roll_no;
  char name[30];
  int phone_number;
};


void display(struct student st)
{
  printf("Roll no : %d\n", st.roll_no);
  printf("Name : %s\n", st.name);
  printf("Phone no : %d\n", st.phone_number);
}


int main()
{
  struct student s;
  s.roll_no = 4;
  strcpy(s.name,"Ron");
  s.phone_number = 888888;
  display(s);
  return 0;
}
Output
Roll no : 4
Name : Ron
Phone no : 888888

In this example, we are printing roll number, name and phone number of a student using function. We first declared a structure named student with roll_no, name and phone number as its members and 's' as its variable. We then assigned the values of roll number, name and phone number to the structure variable s. Just as we pass any other variable to a function, we passed the structure variable 's' to a function 'display'.

Now, while defining the function, we passed a copy of the variable 's' as its argument with 'struct student' written before it because the variable which we have passed is of type structure named student. Finally, in the function, we are printing the name, roll number and phone number of the structure variable.

Passing by Reference


In passing by reference, address of structure variable is passed to the function. In this, if we change the structure variable which is inside the function, the original structure variable which is used for calling the function changes. This was not the case in calling by value.

#include <stdio.h>
#include <string.h>
struct student
{
  int roll_no;
  char name[30];
  int phone_number;
};

void display(struct student *st)
{
  printf("Roll no : %d\n", st -> roll_no);
  printf("Name : %s\n", st -> name);
  printf("Phone no : %d\n", st -> phone_number);
}

int main()
{
  struct student s;
  s.roll_no = 4;
  strcpy(s.name,"Ron");
  s.phone_number = 888888;
  display(&s);
  return 0;
}
Output
Roll no : 4
Name : Ron
Phone no : 888888

This case is similar to the previous one, the only difference is that this time, we are passing the address of structure variable to the function. While declaring the function, our function is taking a pointer of a strucutre 'st'. Since the pointer is of a variable of type structure named 'student', we have written 'struct student' before the name of the pointer in the argument of the function. In the function, we accessed the members of the pointer using -> sign as discussed before.

Try to change the value of variables inside the function in both cases and see the changes in real variables.

Playing card game


Rules of game :
1. First player will select a card.
2. Now, the second player will select a card.
3. If the second player selects a card of the same value as selected by the first player, he will get points.
4. Now, the second player will first select a card and then first player
5. If first player selects a card of the same value as selected by the second player then he will get points.
6. Repeat steps 1 to 5.
7. Player with more score will win the game.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>//for srand and screen clear and echo off and on
#include <time.h>//for shuffling



main()
{
system("clear");//screen clear
int i,j,z,k,lp;
char s,rc;
struct card
{
char *value;
char *suite;
};
struct card temp,list[52],player1[26],player2[26];
//temp for swaping

char *value[] = {"A","2","3","4","5","6","7","8","9","10","K","Q","J"};
char *suite[] = {"diamond","spade","heart","club"};
for (i=0;i<52;i++)
{
if(i<13)
{
list[i].suite=*(suite);
list[i].value=*(value+i);
}
else if(i>=13&&i<26)
{
list[i].suite=*(suite+1);
list[i].value=*(value+(i-13));
}
else if(i>=26&&i<39)
{
list[i].suite=*(suite+2);
list[i].value=*(value+(i-26));
}
else if(i>=39)
{
list[i].suite=*(suite+3);
list[i].value=*(value+(i-39));
}
}


do//do while to ask after game play more ?y or n:
{


//shuffling



int n=52;
srand(time(NULL));
for(i=n-1;i>0;i--)
{
int j=rand()%(i+1);
temp.value=list[i].value;
temp.suite=list[i].suite;
list[i].value=list[j].value;
list[i].suite=list[j].suite;
list[j].value=temp.value;
list[j].suite=temp.suite;
}




//distributing cards
for(i=0;i<52;i++)
{
if(i<26)
{
player1[i].value=list[i].value;
player1[i].suite=list[i].suite;
}
else if(i>=26)
{
player2[i-26].value=list[i].value;
player2[i-26].suite=list[i].suite;
}
}


//for cards info
printf("Player1 has:\t\t\tPlayer2 has:\n");
for (i=0;i<26;i++)
printf("%d\t%s\t%s\t\t%d\t%s\t%s\n",i+1,player1[i].value,player1[i].suite,i+1,player2[i].value,player2[i].suite);




printf("YOUR INPUT WILL NOT BE VISIBLE\n");



int p1score=0,p2score=0;
char a[10],b[10];
char c[10],d[10];



for (j=0;j<26;j++)
{





system("stty -echo");//echo off. input will not be visible





//even value of i will first let player1 to play and odd value to player 2
if(j%2==0)
{


int x=0;
do
{
printf("Player1: type value and suite:");
scanf("%s %s",&a[0],&b[0]);

for (i=0;i<26;i++)
{
//checking if player owns card or not
z=strcmp(player1[i].value,a);
k=strcmp(player1[i].suite,b);

if(z==0&&k==0)
{
//removing used cards
player1[i].value="\0";
player1[i].suite="\0";

x++;
}

}
if (x==0)
printf("ENTER CORRECT CARD\n");
}while(x == 0);


int y=0;
do
{
printf("Player2: type value and suite:");
scanf("%s %s",&c[0],&d[0]);

for (i=0;i<26;i++)
{

z=strcmp(player2[i].value,c);
k=strcmp(player2[i].suite,d);

if(z==0&&k==0)
{
player2[i].value="\0";
player2[i].suite="\0";

y++;
}

}
if (y==0)
printf("ENTER CORRECT CARD\n");
}while(y == 0);







//score if player2 choose same card
lp = strcmp(a,c);

if(lp==0)
p2score=p2score+10;




}




else//if i is odd first turn to player2
{

int y=0;
do
{
printf("Player2: type value and suite:");
scanf("%s %s",&c[0],&d[0]);

for (i=0;i<26;i++)
{

z=strcmp(player2[i].value,c);
k=strcmp(player2[i].suite,d);

if(z==0&&k==0)
{
player2[i].value="\0";
player2[i].suite="\0";

y++;
}

}
if (y==0)
printf("ENTER CORRECT CARD\n");
}while(y == 0);



int x=0;
do
{
printf("Player1: type value and suite:");
scanf("%s %s",&a[0],&b[0]);

for (i=0;i < 26;i++)
{

z=strcmp(player1[i].value,a);
k=strcmp(player1[i].suite,b);

if(z==0&&k==0)
{
player1[i].value="\0";
player1[i].suite="\0";

x++;
}

}
if (x==0)
printf("ENTER CORRECT CARD\n");
}while(x == 0);



lp = strcmp(a,c);

if(lp==0)
p1score=p1score+10;





}

//to see remaining cards

printf("\nPlayer1 has:\t\t\tPlayer2 has:\n");
for (i=0;i<26;i++)
printf("%d\t%s\t%s\t\t%d\t%s\t%s\n",i+1,player1[i].value,player1[i].suite,i+1,player2[i].value,player2[i].suite);



printf("\nPLAYER1 SCORE:%d\tPLAYER2 SCORE:%d\n\n",p1score,p2score);




system("stty echo");//echo on


}





if(p1score>p2score)
printf("PLAYER1 WINS\n");
else if(p1score<p2score)
printf("PLAYER2 WINS\n");
else
printf("MATCH DRAWS\n");



//if one has to play more...do while loop

printf("want to play more? y or n:");
scanf(" %c",&s);
}while(s=='y');

}
Are real games are made like this?
Yes, we have just made the structure of a game to link it to graphics. You can expand your knowledge after completing this course.
Make this better.
Use functions to reduce the length of the code, ask the user for number of players or implement any other idea that you have.
To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.
Without practice, your knowledge is poison.
- Chanakya

Ask Yours
Post Yours
Doubt? Ask question