C•Structs
C Structs: Grouping Heterogeneous Data Records
Structs group related variables of different data types into a single contiguous record.
Syntax
typedef struct {
char name[32];
int port;
} Server;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| struct | Keyword | Defines compound user-defined data type. |
| typedef | Keyword | Creates alias for struct type to avoid writing struct keyword repeatedly. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C locally:
#include <stdio.h>
#include <string.h>
typedef struct {
char hostname[32];
int port;
double latencyMs;
int isOnline;
} NodeConfig;
int main(void) {
NodeConfig primaryNode;
strncpy(primaryNode.hostname, "us-east-cluster-01", sizeof(primaryNode.hostname) - 1);
primaryNode.port = 8080;
primaryNode.latencyMs = 24.5;
primaryNode.isOnline = 1;
printf("Node Hostname: %s\n", primaryNode.hostname);
printf("Port: %d\n", primaryNode.port);
printf("Latency: %.1f ms\n", primaryNode.latencyMs);
printf("Status: %s\n", primaryNode.isOnline ? "ACTIVE" : "INACTIVE");
return 0;
}Expected Output:
Node Hostname: us-east-cluster-01 Port: 8080 Latency: 24.5 ms Status: ACTIVE
How It Works: Step-by-Step
- Lines 4-9: Defines NodeConfig struct with hostname, port, latency, and status fields.
- Lines 12-16: Initializes struct fields using dot . operator.
Key Concepts
- The dot . operator accesses fields on a struct instance.
- typedef struct eliminates the need to prefix variable declarations with struct NodeConfig.
- Structs are passed by value by default (creating a full memory copy unless a pointer is used).
Common Mistake: Assigning strings to char arrays using = instead of strncpy
Array names cannot be assigned to directly in C. Use strncpy or snprintf.
❌ Incorrect
primaryNode.hostname = "new_host"; // Compile Error: assignment to expression with array type
✅ Correct
strncpy(primaryNode.hostname, "new_host", sizeof(primaryNode.hostname));
Related C Tutorials & Compiler
C Arrays: Contiguous Stack Buffers and Multi-Dimensional Arrays
Learn fixed-size arrays, memory layouts, indexing, and calculating element counts.
C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic
Master pointers in C: address-of (&), dereferencing (*), pass-by-reference simulation, and pointer math.
C Strings: Null-Terminated Character Arrays (char[])
Master null-terminated strings (\0), strlen, strcpy, strcat, and strcmp from string.h.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.