This post was first published on Jupius Learning, where you can read it free with diagrams and practice exercises.
Subscribe to our articles for regular updates.
In the last post I wrote things like s->ops->area(s) and file->f_op->read without stopping to explain them. That is where this post starts. We look at a pointer to a struct on its own, what the arrow operator does, and why the Linux kernel passes and links its structs by pointer almost everywhere.
If you have read the first post in this series, you know the dot operator. You use it when you have the struct itself. This post is about the other case, when all you have is the address of the struct.
All the output in this post comes from gcc 14 on a 64-bit x86 Linux machine. The kernel snippets are copied from recent mainline source and trimmed.
What is a pointer to a struct in C?
A pointer to a struct is a variable that holds the address of a struct. You declare it with a *, the same as any other pointer, and you fill it with &.
#include <stdio.h>
struct student {
int id;
char grade;
double score;
};
int main(void)
{
struct student s = { 42, 'A', 91.5 };
struct student *p = &s;
printf("s.id = %d\n", s.id);
printf("(*p).id = %d\n", (*p).id);
printf("p->id = %d\n", p->id);
p->score = 95.0;
printf("s.score after p->score = 95.0: %.1f\n", s.score);
printf("sizeof(s) = %zu\n", sizeof(s));
printf("sizeof(*p) = %zu\n", sizeof(*p));
printf("sizeof(p) = %zu\n", sizeof(p));
printf("p == &s: %s\n", p == &s ? "yes" : "no");
return 0;
}
Save it as ptr_basic.c, then compile and run it:
gcc ptr_basic.c -o ptr_basic
./ptr_basic
In PowerShell with MinGW, run it with .\ptr_basic.exe.
Output:
s.id = 42
(*p).id = 42
p->id = 42
s.score after p->score = 95.0: 95.0
sizeof(s) = 16
sizeof(*p) = 16
sizeof(p) = 8
p == &s: yes
p points at s. It is not a copy. When we write p->score = 95.0, the score inside s changes, and the next line proves it.
Look at the sizes. sizeof(s) and sizeof(*p) are both 16, because *p is the struct that p points at. The pointer itself, sizeof(p), is 8 bytes on a 64-bit machine. It does not matter how big the struct is. The pointer stays 8 bytes. Why the struct is 16 and not 13 is the story of the padding post.
What does the arrow operator do?
The arrow operator -> is a short way to write "go to the struct this pointer points at, then take this field". These two lines mean exactly the same thing:
(*p).id
p->id
*p follows the pointer and gives you the struct. Then .id picks the field. The brackets are needed, and that is the reason -> exists.
The dot binds tighter than the star. So *p.id is read as *(p.id). That asks for the field id of p, and then tries to follow it as a pointer. But p is a pointer, not a struct, so it has no fields. Here is what gcc says:
printf("%d\n", *p.id);
bad_dot.c: In function 'main':
bad_dot.c:13:22: error: 'p' is a pointer; did you mean to use '->'?
13 | printf("%d\n", *p.id);
| ^
| ->
The compiler even suggests the fix. The rule is easy to remember:
- Use
.when you have a struct variable. - Use
->when you have a pointer to a struct.
Both can show up in one expression. If a struct holds another struct inside it, as in the nesting post, you use an arrow for the pointer and then a dot for the inner struct, like p->addr.pin. We will see the kernel do exactly that later.
Why pass a struct by pointer, in C and in the Linux kernel?
When you pass a struct to a function by value, C copies the whole struct. The function works on its own copy. Whatever it changes is lost when it returns.
#include <stdio.h>
struct stats {
int count;
int samples[16];
};
static void add_copy(struct stats s, int v)
{
s.samples[s.count] = v;
s.count++;
}
static void add_ptr(struct stats *s, int v)
{
s->samples[s->count] = v;
s->count++;
}
static int total(const struct stats *s)
{
int i, sum = 0;
for (i = 0; i < s->count; i++)
sum += s->samples[i];
return sum;
}
int main(void)
{
struct stats st = { 0 };
add_copy(st, 10);
printf("after add_copy: count = %d\n", st.count);
add_ptr(&st, 10);
add_ptr(&st, 25);
printf("after add_ptr: count = %d, total = %d\n", st.count, total(&st));
printf("sizeof(struct stats) = %zu\n", sizeof(struct stats));
printf("sizeof(struct stats *) = %zu\n", sizeof(struct stats *));
return 0;
}
Output:
after add_copy: count = 0
after add_ptr: count = 2, total = 35
sizeof(struct stats) = 68
sizeof(struct stats *) = 8
add_copy did its work on a copy, so st.count is still 0. add_ptr got the address of st, so it changed the real thing.
There is a second reason, and it is size. Calling add_copy copies 68 bytes on every call. Calling add_ptr passes 8. For a small struct the difference is tiny. For a struct with hundreds of fields it is not.
The total function takes a const struct stats *. The const is a promise that the function will only read through the pointer. If it tries to write, the compiler stops it:
const_bad.c: In function 'reset':
const_bad.c:7:14: error: assignment of member 'count' in read-only object
7 | s->count = 0;
| ^
You will see const struct in a lot of kernel function signatures for this reason. It tells the reader that the function only looks at the struct.
Pointers to structs on the heap and in arrays
A pointer can also point at memory you ask for at run time. For a struct, the usual way to write the size is sizeof *p. That way the line stays right even if you later change the type of p.
Pointers also work with arrays of structs. Adding 1 to a struct pointer moves it forward by one whole struct, not by one byte.
#include <stdio.h>
#include <stdlib.h>
struct item {
int id;
int qty;
};
int main(void)
{
struct item *p = malloc(sizeof *p);
if (p == NULL)
return 1;
p->id = 7;
p->qty = 3;
printf("heap item: id = %d, qty = %d\n", p->id, p->qty);
free(p);
struct item shelf[3] = { { 1, 10 }, { 2, 20 }, { 3, 30 } };
struct item *q = shelf;
printf("q->qty = %d\n", q->qty);
printf("(q + 1)->qty = %d\n", (q + 1)->qty);
printf("q[2].qty = %d\n", q[2].qty);
printf("step between items = %td bytes\n",
(char *)(q + 1) - (char *)q);
q++;
printf("after q++, q->id = %d\n", q->id);
return 0;
}
Output:
heap item: id = 7, qty = 3
q->qty = 10
(q + 1)->qty = 20
q[2].qty = 30
step between items = 8 bytes
after q++, q->id = 2
struct item is 8 bytes, so q + 1 is 8 bytes after q. The compiler does that multiplication for you. Notice q[2].qty too. The square brackets already follow a pointer, so you use a dot after them, not an arrow.
Check the result of malloc before you use it, as the code does. If it returns NULL and you write p->id, you are using a pointer that points at nothing. We come back to that near the end.
How the Linux kernel finds the running process with current
Now the kernel. Every piece of kernel code that runs on behalf of a process can use a name called current. It is a pointer to the struct task_struct of the process that is running on this CPU right now. If you have not met that struct yet, the task_struct post goes through its fields.
On x86 it looks like this:
/* From the Linux kernel, arch/x86/include/asm/current.h (trimmed) */
struct task_struct;
static __always_inline struct task_struct *get_current(void)
{
if (IS_ENABLED(CONFIG_USE_X86_SEG_SUPPORT))
return this_cpu_read_const(const_current_task);
return this_cpu_read_stable(current_task);
}
#define current get_current()
Each CPU keeps its own pointer to the task it is running. current just reads it. You can ignore the per-CPU details for now. The point is that current has the type struct task_struct *. So every use of it needs the arrow.
Here is the real code behind two system calls you know from user space, from kernel/sys.c:
/* From the Linux kernel, kernel/sys.c */
SYSCALL_DEFINE0(getpid)
{
return task_tgid_vnr(current);
}
SYSCALL_DEFINE0(getppid)
{
int pid;
rcu_read_lock();
pid = task_tgid_vnr(rcu_dereference(current->real_parent));
rcu_read_unlock();
return pid;
}
getpid hands the current pointer to a helper. getppid follows the arrow from current to its real_parent field and asks for the process ID of whatever that is. The rcu_ lines make that read safe while other code may be changing the parent. Do not worry about them yet. The part we care about is current->real_parent.
Notice that the parent is also a struct task_struct *. A task points at another task. That is the next idea.
Linking Linux kernel structs by pointer: parent and real_parent
Here are the fields of task_struct that hold the family tree, trimmed from include/linux/sched.h:
/* From the Linux kernel, include/linux/sched.h, in struct task_struct (trimmed) */
pid_t pid;
pid_t tgid;
/* Real parent process: */
struct task_struct __rcu *real_parent;
/* Recipient of SIGCHLD, wait4() reports: */
struct task_struct __rcu *parent;
/*
* Children/sibling form the list of natural children:
*/
struct list_head children;
struct list_head sibling;
struct task_struct *group_leader;
Look at the types. real_parent and parent are pointers to a task_struct. So is group_leader. None of them is a task_struct stored inside a task_struct. C does not allow that. A struct cannot contain itself, because it would have to be infinitely big. Here is what gcc says if you try:
struct proc {
int pid;
struct proc parent;
};
self_embed.c:3:17: error: field 'parent' has incomplete type
3 | struct proc parent;
| ^~~~~~
A pointer to the same struct is fine, because a pointer has a fixed size no matter what it points at. That is how a struct can refer to another one of its own kind.
The children and sibling fields are list_head structs, which are embedded, not pointed at. That is the container_of trick from the nesting post. So task_struct uses both styles side by side. A pointer says "this one is somewhere else, go and find it". An embedded struct says "this is part of me".
Here is the same idea as a small user-space program. The names copy the kernel, but this is not kernel code.
#include <stdio.h>
struct proc {
int pid;
const char *name;
struct proc *parent;
};
static void show_chain(const struct proc *p)
{
for (; p != NULL; p = p->parent)
printf("%d %s\n", p->pid, p->name);
}
int main(void)
{
struct proc init = { 1, "init", NULL };
struct proc shell = { 812, "bash", &init };
struct proc edit = { 2040, "vim", &shell };
show_chain(&edit);
printf("edit.parent->name = %s\n", edit.parent->name);
printf("edit.parent->parent->name = %s\n", edit.parent->parent->name);
printf("sizeof(struct proc) = %zu\n", sizeof(struct proc));
return 0;
}
Output:
2040 vim
812 bash
1 init
edit.parent->name = bash
edit.parent->parent->name = init
sizeof(struct proc) = 24
The loop in show_chain is the whole trick. p = p->parent moves the pointer one step up the tree. When it reaches init, whose parent is NULL, the loop ends. A NULL pointer is how C says "there is nothing more here".
The two printf lines at the end chain arrows. edit.parent->parent->name reads left to right. Start with edit, take its parent pointer, follow it, take that struct's parent pointer, follow it, and read the name. Each arrow is one hop.
The numbers here are made up for the demo. In a real system the top of the tree is usually the process with ID 1, and the other processes lead back to it through their parents.
Read the rest on Jupius
That covers what a pointer to a struct is, why the arrow operator exists, why functions take struct pointers, and how a struct can point at another one of its own kind, including the parent pointers in task_struct. The second half of the post stays with the Linux kernel. It shows why tasks share an mm_struct through a pointer, how long chains of arrows work, from an open file down to its inode number, and a short kernel module that reads current. It also shows what goes wrong if you use the arrow operator on a NULL pointer, and it ends with practice exercises.
Read the full post on Jupius Learning. It is free, with every example, the diagrams and the practice exercises.
If you want to practice structs with small exercises that check your code as you go, the C programming course at Jupius Learning covers them step by step.
Top comments (0)