Language 1 of 10 · Topic 0.9

Core Sequential Collections: Fixed Arrays, Strings & Structs

1Concept

C arrays are contiguous memory blocks. Array names decay to pointers to their first element. Strings in C are null-terminated character arrays ('\0'). Structs group heterogeneous data types with compile-time memory alignment and padding.

2Architecture Diagram

String in Memory: "HELLO"
['H'] ['E'] ['L'] ['L'] ['O'] ['\0']
  0     1     2     3     4     5   (Length = 5, Sizeof = 6 bytes)

3Code Example

Stage 0 Language Foundations
#include <stdio.h>
#include <string.h>

typedef struct {
    int id;
    char name[32];
    double gpa;
} Student;

int main(void) {
    Student s1 = { .id = 101, .gpa = 3.85 };
    strncpy(s1.name, "Alexander Hamilton", sizeof(s1.name) - 1);
    s1.name[sizeof(s1.name) - 1] = '\0'; // Ensure null-termination

    printf("Student Record:\n");
    printf("ID: %d | Name: %s | GPA: %.2f\n", s1.id, s1.name, s1.gpa);
    printf("Struct sizeof: %zu bytes\n", sizeof(Student));

    return 0;
}

4Expected Output

Student Record:
ID: 101 | Name: Alexander Hamilton | GPA: 3.85
Struct sizeof: 48 bytes

5Key Takeaways

  • Strings in C MUST be terminated with '\0' to prevent buffer overrun.
  • Use strncpy / snprintf instead of unsafe strcpy / sprintf.
  • Structs may have padding bytes inserted by the compiler for CPU alignment.