Structures

C Language

Introduction

Structures are another data type in C that allows you to group information and other variables. In this lesson, we will discuss the basic uses of structures in C and using structures with pointers.


Structures

Structures allows you to create a type of data that you can define that can group other information and variables so that you can access them easily. For example, we can create a structure student, and put members such as name, grade, score, id_num in the structure. This way, we can create instances of the structure such as stud_1, stud_2, or even an array struct student: class_1 [30]. You can use structures to make your program clearer, help to organize your variables, and also it is very helpful for you to group the information and access it through the structure.

Declaration

For a structure to be used, you need to first declare what variables are in them (a structure can contain one or more variables). Here is the basic structure of the declaration:
struct structure_name
{
Members
};
For example:
struct student
{
char *name;
int grade;
float score;
long int id_num;
};
As you see here, after the keyword struct is the name of your structure. Then brackets follow, and the list of members that are in that structure. Because this is a declaration, remember to put semicolon at the end of the closing bracket. Structures are typically declared globally (usually at the top of your program after preprocessors before functions) so that every function can create instances of that structure (local structures can also be declared, just put them inside a function). You cannot initialize values in a declaration.

Creating Instances

Now we've declared a structure student, but we didn't declare any variables that are type struct student. A variable created of type struct student is called an instance of struct student. Let's look at a program to explain the basic uses of structures.

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

struct student
{
  char name [20];
  int grade;
  float score;
  long int id_num;
};

int main()
{
  struct student stud_1,stud_2;
  strcpy(stud_1.name,"Michael");
  strcpy(stud_2.name,"Frank");
  stud_1.grade=8;
  stud_2.grade=7;
  stud_1.score=97.83;
  stud_2.score=95.64;
  stud_1.id_num=1103907l;
  stud_2.id_num=11046833;
  printf("%ld: %s (%d) %f\n",stud_1.id_num,stud_1.name,stud_1.grade,stud_1.score);
  printf("%ld: %s (%d) %f\n",stud_2.id_num,stud_2.name,stud_2.grade,stud_2.score);
}

1103907: Michael (8) 97.110001
11046833: Frank (7) 95.000000

The example above demonstrates the very basic use of structures in C. We declared a structure student to store information about a student. Then, we created two instances of the structure student, called stud_1 and stud_2. Creating instances of structures is same as variable declarations since you defined a "variable type" struct student. Therefore, the variable type in the declaration is struct student. By declaring the two instances, we created two groups of variables, stud_1 and stud_2, each containing a variable name, a grade, a score, and an id_num.

To access values in members of instances of structures, you would first need to state which instance the members belongs to, a period, and the name of the member.

Structures become much more useful when you create an array of them, for example, we can create a "class" or struct student:

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

struct student
{
  char name [20];
  int grade;
  float score;
  long int id_num;
};

void input(struct student *stud)
{
  printf("Enter name:");
  scanf("%s",stud->name); /*Access through pointer uses "->" instead of '.'*/
  printf("Enter grade:");
  scanf("%d",&(stud->grade)); /*Although stud is an address, stud->grade isn't, so we need '&'*/
  printf("Enter score:");
  scanf("%f",&(stud->score));
  printf("Enter id_num:");
  scanf("%ld",&(stud->id_num));
}

int main()
{
  struct student class [30]; /*Creates an array of struct student variables (a class of 30 students)*/
  int i;

  for(i=0;i<30;i++)
   {
     input(class+i); /*We created an array of struct student variables, so class+i is address of ith
instance*/
   }

  for(i=0;i<30;i++)
   {
  	 printf("%ld: %s (%d) %f\n",class [i].id_num,class [i].name,class [i].grade,class [i].score);
	 /*class [i] rather than class+i accesses the value rather than address, so we used '.'*/
   }
}

Enter name:Michael
Enter grade:8
Enter score:98
Enter id_num:289328
Enter name:Frank
Enter grade:8
Enter score:97
Enter id_num:239822
Keep inputting...
289328: Michael (8) 98.000000
239822: Frank (8)97.000000
More outputs...

This examples demonstrated two new ways to use structures. We created an array of struct student with: struct student class [30]; Here, we created an array with 30 elements of type struct student variables, each containing name, grade, score, and id_num. By creating an array of stuctures, we can conveniently access them through a loop and create a large amount of structures. The second new way to access structures is to use pointers, shown above. Instead of using '.' to access a member, when you have a pointer, you "->" (a hyphen and a greater than sign). In the example above, we created an array of struct student, therefore class+i is the address of the ith element in the array. We can use struct_pointer_name->member_name to access a member.

Let's look at an example:

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

struct str
{
  char *txt;
  int len;
};

struct str *append(struct str *original,struct str *add)
{
  int tlen=original->len+add->len;
  struct str *result=malloc(sizeof(struct str));
  int i,mark;
  result->txt=malloc(sizeof(char)*tlen);
  result->len=tlen;
  for(i=0;*(original->txt+i)!='\0';i++)
    {
      *(result->txt+i)=*(original->txt+i);
    }
  for(mark=i,i=0;*(add->txt+i)!='\0';i++)
    {
      *(result->txt+i+mark)=*(add->txt+i);
    }
  *(result->txt+i+mark)='\0';
  return result;
}

int main()
{
  struct str original,add;
  original.len=strlen("Abacles C Programming Tutorial");
  original.txt=malloc(sizeof(char)*original.len);
  strcpy(original.txt,"Abacles C Programming Tutorial");
  add.len=strlen(" Structures Lesson");
  add.txt=malloc(sizeof(char)*add.len);
  strcpy(add.txt," Structures Lesson");
  printf("%s + %s\n= %s\n",original.txt,add.txt,append(&original,&add)->txt);
}

Abacles C Programming Tutorial Structures Lesson

Practice

Declare a structure with 3 members, create an instance through pointers and malloc. Print out the addresses of each member in the structure.

Declare a structure str with char *txt and int len. Allows the user to input a length, then the string, and also two characters. Use a function to search for the first character in the string, and replace them with the second character.

Declare a structure point with members x and y (int), then declare crcl with members radii and radius (int), in which radii is type struct point (containing x and y). User inputs the information about the circle, then input a translation (formatted %c%d, such as u5 for up 5,d3 for down 3,l2 for left 2, and r23 for right 23). Program prints out the area and circumference of the circle, and the translated coordinates for radii.

Additional practice on preprocessers:

Activity 18.2

<< Previous TOC Next >>