Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Structs in C

Tech 1

Definition

A structure (or struct) is a composite type composed of several members, each of which can be a basic data type or another composite type.

Since a structure is a constructed data type, it must be defined before use, similar to how functions must be defined before invocation.

Why Use Structs?

Structs allow you to organize related data together, making it convenient to manage. When passing multiple parameters to a function, using a struct simplifies the call. Many system functions require structs.

Defining a Struct

// General form:
struct structure_name {
    member_list;
};

// Example: define a student struct
struct stu {
    int num;
    char name[10];  // or char *name;
};

Declaring Struct Variables

There are three ways to declare struct variables:

  1. Define struct first, then declare variables

    struct Student {
        int sno;            // student ID
        char name[20];      // student name
        int age;            // age
        float score;        // score
    };
    // Note: Defining a struct does not allocate memory; memory is allocated when a variable is declared.
    
    // Declaration format:
    struct Student stu1;
    
  2. Define struct and declare variables simultaneously

    struct Student {
        int sno;
        char name[20];
        int age;
        float score;
    } stu1, stu2;  // declare variable(s) here
    
  3. Using an anonymous struct

    struct {
        int sno;
        char name[20];
        int age;
        float score;
    } stu1, stu2;
    

Accessing Struct Members

Members are accessed using the dot operator:

struct_variable.member_name

Initializing Struct Variables

struct Student {
    int sno;
    char name[21];
    int age;
    float score;
};

// Method 1: Assign after declaration
struct Student stu;
stu.sno = 1;
// stu.name = "abc";  // Error: cannot assign to array directly
strcpy(stu.name, "abc");
stu.score = 59.99f;

// Method 2: Initialize at declaration (order must match)
struct Student stu2 = {8, "哈哈", 2, 4.5f};

// Note on Chinese characters:
// In UTF-8, each Chinese character takes 3 bytes (default in Xcode)
// In GB2312/GBK, each Chinese character takes 2 bytes

Memory Layout of Structs

The total memory occupied by a struct is the sum of the sizes of its members, considering alignment.

Calculating Struct Size

// Steps:
// 1. Sum the lengths of all data members: sum_a
// 2. Add padding bytes for each member to align to its alignment modulus: sum_b
//    (alignment modulus = min(#pragma pack value, member's natural size))
// 3. Align sum_b to the struct's alignment modulus (min(#pragma pack, largest member size))

// Example:
struct A {
    int a;       // 4 bytes
    char b;      // allocates 4 bytes, uses 1, leaves 3
    short c;     // needs 2 bytes, place after padding if needed
};

printf("%zu\n", sizeof(struct A));  // typically 8 on many systems

// Simplified rule:
// Find the largest basic data type in the struct (alignment modulus).
// Calculate the total bytes used by all members, considering alignment.

Enum (Another Kind of Struct)

An enumeration is a basic data type, not a composite type.

// General form:
enum enum_name { value1, value2, ... };

// The compiler assigns integer values automatically:
// First element = 0, subsequent elements are previous +1.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.