C-STRUCTURES

Dev Frank
9 min readMay 12, 2024

--

Hi there, folks! Today we’re going to explore one of the most powerful and flexible features of the C programming language: Structures!

Think of a structure like a digital container that can hold multiple values of different types, like a student's name, age, and grade. It's like a labeled folder that keeps all the related information together, making it easy to access and manipulate.

C Structures are game-changer when it comes to organizing and managing complex data. They allow you to define your own custom data types, making your code more readable, efficient, and scalable.

In this topic, we'll dive into the world of C Structures, covering the basics, advanced techniques, and real-world examples. Whether you're a beginner or an experienced programmer, you'll learn how to harness the power of structures to write more effective and elegant code.

So, let’s get started and discover the awesomeness of C Structures together!

SO WHAT IS C -STRUCTURE ?

A C structure is a user-defined data type in the C programming language that allows you to combine multiple variables of different types into a single unit. It's a way to organize and store related data together, making it easier to access and manipulate.

Structures can store various data types, unlike arrays, which are restricted to a single data type.

A C structure is defined using the struct keyword, followed by the name of the structure and a list of members (variables) enclosed in curly braces { }.

Syntax Of A C-Structure

The basic syntax for a C structure is:

struct struct_name {
member1_Datatype member1_name;
member2_Datatype member2_name;
...
memberN_Datatype memberN_name;
};

Here:

  • struct is the keyword used to define a structure.
  • struct_name is the name given to the structure.
  • member1_Datatype and member1_name are the data type and name of the first member (variable) of the structure.
  • member2_Datatype and member2_name are the data type and name of the second member (variable) of the structure.
  • ... represents additional members (variables) of the structure.
  • memberN_Datatype and memberN_name are the data type and name of the Nth member (variable) of the structure.

Note:

The structure name and member names must follow C’s identifier rules (e.g., start with a letter or underscore, contain only letters, digits, and underscores).
The members of a structure can be of different data types, including primitive types (e.g., int, char, float), pointer types, and even other structures.
A structure can also contain functions (called "methods" in some languages) as members, but this is less common in C.

For example:

struct Student {
char name[50];
int age;
float grade;
};

To use a structure, you need to declare a variable of the structure type:

struct Student s1;

This creates a variable s1 of type struct Student, which has members name, age, and grade. You can then access and manipulate these members using the dot notation:

s1.name = "John";
s1.age = 20;
s1.grade = 85.5;

This defines a structure named Student with three members: name (a character array), age (an integer), and grade (a floating-point number).

Let’s look at another example

#include <stdio.h>

// Define a structure
struct Point {
int x;
int y;
};

int main() {
// Method 1: Initialization at declaration
struct Point p1 = {10, 20};

// Method 2: Initialization after declaration
struct Point p2;
p2.x = 30;
p2.y = 40;

// Displaying values
printf("p1: x = %d, y = %d\n", p1.x, p1.y);
printf("p2: x = %d, y = %d\n", p2.x, p2.y);

return 0;
}

OUTPUT

p1: x = 10, y = 20
p2: x = 30, y = 40

In this example, p1 is initialized at the time of declaration using curly braces { } to assign values to its members x and y. p2 is declared first and then initialized by assigning values to its members individually.

C- Structure is so cool that you conveniently create multiple variables, each holding different values, all using the same structure definition. Let me illustrate this with a simple program:

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

// Define a structure named "Person"
struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare variables of type "struct Person"
struct Person person1, person2;

// Assign values to members of "person1"
strcpy(person1.name, "Alice");
person1.age = 30;
person1.height = 5.5;

// Assign values to members of "person2"
strcpy(person2.name, "Bob");
person2.age = 25;
person2.height = 6.0;

// Print details of "person1"
printf("Person 1\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n\n", person1.height);

// Print details of "person2"
printf("Person 2\n");
printf("Name: %s\n", person2.name);
printf("Age: %d\n", person2.age);
printf("Height: %.2f\n", person2.height);

return 0;
}

OUTPUT

Person 1
Name: Alice
Age: 30
Height: 5.50

Person 2
Name: Bob
Age: 25
Height: 6.00

In this program:

  1. We define a structure named Person with members name, age, and height.
  2. Inside the main function, we declare two variables of type struct Person: person1 and person2.
  3. We assign values to the members of person1 and person2 using the dot (.) operator.
  4. Finally, we print the details of both person1 and person2, showing how each variable holds different values even though they are of the same structure type.

I guess you saw the function strcpy( ) in the above example and you might be wondering WHAT IS IT USED FOR?

strcpy( )

The full name for strcpy is "string copy". It is a standard C library function used for copying strings from one location to another.

Its prototype is declared in the <string.h> header file:

syntax

char *strcpy(char *destination, const char *source);

destination: Pointer to the destination array where the string is to be copied.
source: Pointer to the source string to be copied.
The function copies the string pointed to by source (including the null terminator) to the array pointed to by destination. It returns a pointer to the destination string.

NOTE:

In the function's strcpy() prototype, the char datatype at the front is not strictly necessary for understanding the function's usage. It simply indicates that the function returns a pointer to a character (char) data type, which is the destination string after the copy operation.

The essential parts of the strcpy() function are the two parameters: char *destination and const char *source, which specify the destination and source strings, respectively. The char * indicates that both destination and source are pointers to characters, allowing the function to manipulate strings.

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

int main() {
char source[] = "Hello, World!";
char destination[20];

// Copy the string from source to destination
strcpy(destination, source);

// Print the copied string
printf("Copied string: %s\n", destination);

return 0;
}

OUTPUT

Copied string: Hello, World!

SO WHY USE strcpy() ?

Going back to the example above where we use the strcpy() function but this time around we are not using the strcpy() function

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

// Define a structure named "Person"
struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare variables of type "struct Person"
struct Person person1, person2;

// Assign values to members of "person1"
person1.name = "Alice"; // Error: Cannot assign a value to an array

person1.age = 30;
person1.height = 5.5;

// Assign values to members of "person2"
person2.name = "Bob"; // Error: Cannot assign a value to an array

person2.age = 25;
person2.height = 6.0;

// Print details of "person1"
printf("Person 1\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n\n", person1.height);

// Print details of "person2"
printf("Person 2\n");
printf("Name: %s\n", person2.name);
printf("Age: %d\n", person2.age);
printf("Height: %.2f\n", person2.height);

return 0;
}

Remember strings in C are arrays of characters. However, directly assigning a value to an array isn’t possible in C. So the compiler will spit out an error message:

prog.c:15:21: error: assignment to expression with array type
prog.c:21:21: error: assignment to expression with array type

This error occurs because you cannot directly assign a string literal (of type const char *) to an array of characters (of type char[50]).

So what the strcpy() function did was, it copied the string literals “Alice” and “Bob” into the name member of person1 and person2 structures, respectively. After these calls, person1.name will contain the string “Alice”, and person2.name will contain the string “Bob”.

SHORTHAND ASSIGNMENT

Assigning values to structure members during declaration is possible by enclosing the values in curly braces { }.

Have in mind that you don’t have to use strcpy() function for string values with this technique. For instance:

// Create a structure
struct Human{
int age;
float height;
char[50] name;
};
int main() {
struct Human p1 = {10, 4.5, "Frank"}; // // Create a structure variable and assign values to members during declaration

// Print values
printf("Age: %d, Height: %.2fft, Name: %s", p1.age, p1.height, p1.name);

return 0;
}

OUTPUT

Age: 10, Height: 4.5ft, Name: Frank

NOTE:

Ensure that the order of the inserted values aligns with the order of the variable types declared in the structure. For example, if you have an integer (int) followed by a character (char), make sure the values are inserted in the same order (e.g., 10 for int and ‘B’ for char).

NESTED STRUCTURE

A nested structure in C is a structure that is defined within another structure. This allows you to group related data together in a hierarchical manner, where one structure’s members can include another structure as one of its members.

Here’s the syntax for defining a nested structure:

struct OuterStructure {
// Members of the outer structure
int outerMember1;
float outerMember2;

// Nested structure declaration
struct InnerStructure {
// Members of the inner structure
int innerMember1;
char innerMember2;
} nestedStruct; // Declaration of a variable of the nested structure type
};

In this syntax:

  • OuterStructure is the name of the outer structure.
  • Inside OuterStructure, we define another structure named InnerStructure.
  • InnerStructure is defined within OuterStructure, making it a nested structure.
  • The members innerMember1 and innerMember2 belong to the InnerStructure.
  • nestedStruct is a variable of type InnerStructure declared within OuterStructure.

Let’s look at an example

#include <stdio.h>

// Define a structure for a point
struct Point {
int x;
int y;
};

// Define a structure for a rectangle
struct Rectangle {
struct Point topLeft;
struct Point bottomRight;
};

int main() {
// Declare a variable of type Rectangle
struct Rectangle rect;

// Assign values to members of rect
rect.topLeft.x = 10;
rect.topLeft.y = 20;
rect.bottomRight.x = 100;
rect.bottomRight.y = 80;

// Access and print the values
printf("Top left corner: (%d, %d)\n", rect.topLeft.x, rect.topLeft.y);
printf("Bottom right corner: (%d, %d)\n", rect.bottomRight.x, rect.bottomRight.y);

return 0;
}

In this example:

  • We define a structure Point representing a point in 2D space with x and y coordinates.
  • We then define another structure Rectangle, where each corner is represented by a Point structure.
  • In the main function, we declare a variable rect of type Rectangle.
  • We assign values to the x and y members of topLeft and bottomRight, which are themselves structures of type Point.
  • Finally, we print the coordinates of the top-left and bottom-right corners of the rectangle.

Passing structures to functions in C

Passing structures to functions in C involves sending structure data as arguments to functions.

Passing structures to functions in C allows you to manipulate and operate on complex data types within functions. When passing a structure to a function, you can either pass the structure directly or pass a pointer to the structure.

This is how you can pass a structure to a function:

#include <stdio.h>

// Define a structure
struct Point {
int x;
int y;
};

// Function that takes a structure as an argument
void printPoint(struct Point p) {
printf("Point: (%d, %d)\n", p.x, p.y);
}

int main() {
// Declare and initialize a structure variable
struct Point p1 = {10, 20};

// Call the function and pass the structure
printPoint(p1);

return 0;
}

Passing Structure Pointer:

#include <stdio.h>

// Define a structure
struct Point {
int x;
int y;
};

// Function that takes a pointer to a structure as an argument
void printPoint(struct Point *p) {
printf("Point: (%d, %d)\n", p->x, p->y);
}

int main() {
// Declare and initialize a structure variable
struct Point p1 = {10, 20};

// Call the function and pass a pointer to the structure
printPoint(&p1);

return 0;
}

In both examples, the printPoint function takes a struct Point as an argument. In the first example, the structure is passed directly, while in the second example, a pointer to the structure is passed.

When passing structures directly, a copy of the structure is made, so any modifications made to the structure inside the function won’t affect the original structure.

When passing a pointer to a structure, you’re working directly with the original structure, so modifications made inside the function will reflect in the original structure outside the function. Passing pointers can be more efficient for large structures since you’re not copying the entire structure.

Some key features of C structures include:

  1. Members can be of different data types
  2. Members can be accessed using the dot notation (e.g., `student.name`)
  3. Structures can be assigned, passed to functions, and returned from functions
  4. Structures can be used in arrays and pointers
  5. Structures can be nested (one structure can contain another structure as a member)

You’ve made it to the end and gotten smarter by learning about C Structures. Now, try using what you’ve learned. Good luck!

If you enjoyed this journey and would like to show your support, here’s how you can:

  1. Follow me on Medium for more insightful content.
  2. Connect with me on X, LinkedIn, and GitHub, where I consistently share valuable programming resources for free.

--

--

Dev Frank

Passionate tech enthusiast, diving deep into the world of software engineering. Thrilled to share insights with the world. A Software engineering student.