Pointers and Structures

Filter Course


Pointers and Structures

Published by: Zaya

Published date: 18 Jun 2021

Pointers and Structures Photo

Pointers and Structures

If you are working on a program to store video game purchases, you have several options. You could create dozens of variables needed to describe a game (title, rating, price, levels, difficulty, etc.). Pointers and Structures Another option is to create a struct to hold each video game in its container.

A struct is used to store variables of several different types together in a single object. Because we are in the world of C, we can’t use objects and classes, but the struct is pretty darn close and is a great tool to have in the toolbox.

In this lesson, we’ll be creating a simple struct to hold our video game purchases. Our structure will contain:

  • The game console the video game runs on
  • The game’s ESRB rating
  • How much it retails the following is a fully functioning C program and was compiled using Dev C++. The struct gets defined before the main function. Next, in the main function, we create a new instance of the game and call it fallout. We then update the member variables in the struct.

#include
//create the struct
struct game {
char console[50];
char rating[2];
float price;
};
int main() {
struct game fallout;
strcpy(fallout.console, “XBOX”);
strcpy(fallout.rating, “M”);
return 0;
}

Since it is a character array we also use the strcpy function. Before we move on to structs and pointers, let’s quickly take another look at pointers in C.

Pointers
A pointer in C is something that points to something else. In most cases, this means that it points to an address in memory. Figure 1 shows the basics of a pointer.

Pointers
The following code shows the creation of a pointer. You create a pointer with an asterisk (e.g., *rating). You dereference a pointer to get to the address of the pointee (the thing you are pointing to). The ampersand (&) is used to do this. In the code, we create a pointer and an integer, then point to that integer’s address.

#include
int main() {
//create the pointer
int *ptr;
int x = 5;
//dereference
;ptr = &x;
//5 will print
printf(“%d”, *ptr);
printf(“\n”);
//address will print
printf(“%x”, &ptr);
return 0;
}
Now that we have a struct (video game), and have reviewed the creation of pointers, let’s look at how pointers and structs can work together.