C•Struct Pointers
C Struct Pointers and Arrow Operator (->)
Learn how to pass structs to functions by pointer to avoid memory copy overhead and mutate fields in place.
Syntax
struct_ptr->member_name = value;
// Equivalent to: (*struct_ptr).member_name
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| -> | Arrow Operator | Dereferences struct pointer and accesses member in one step. |
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 workerName[32];
int tasksCompleted;
int isHealthy;
} WorkerNode;
// Function accepting struct pointer (mutates original)
void recordTaskCompletion(WorkerNode* node) {
node->tasksCompleted++;
printf("[NODE %s] Completed task. Total: %d\n",
node->workerName, node->tasksCompleted);
}
int main(void) {
WorkerNode worker;
strncpy(worker.workerName, "Worker-Alpha", sizeof(worker.workerName));
worker.tasksCompleted = 0;
worker.isHealthy = 1;
// Pass address of worker
recordTaskCompletion(&worker);
recordTaskCompletion(&worker);
return 0;
}Expected Output:
[NODE Worker-Alpha] Completed task. Total: 1 [NODE Worker-Alpha] Completed task. Total: 2
How It Works: Step-by-Step
- Lines 11-15: Accepts WorkerNode* and updates field via node->tasksCompleted++.
- Line 24-25: Passes address &worker to avoid copying struct.
Key Concepts
- ptr->member is syntactic sugar for (*ptr).member.
- Passing structs by pointer avoids copying potentially large structs on the stack.
Common Mistake: Using dot . on a pointer instead of arrow ->
p.member fails compilation if p is a pointer; you must use p->member.
❌ Incorrect
WorkerNode* p = &worker; p.tasksCompleted++; // Compile Error: request for member in something not a structure
✅ Correct
p->tasksCompleted++; // Correct
Related C Tutorials & Compiler
C Structs: Grouping Heterogeneous Data Records
Define compound records in C using struct and typedef struct.
C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic
Master pointers in C: address-of (&), dereferencing (*), pass-by-reference simulation, and pointer math.
C Dynamic Memory: malloc, calloc, realloc, and free
Allocate heap memory dynamically at runtime using malloc, calloc, realloc, and free.
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.