C:C Structs: Grouping Heterogeneous Data Records
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:

ParameterTypeDescription
structKeywordDefines compound user-defined data type.
typedefKeywordCreates alias for struct type to avoid writing struct keyword repeatedly.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler