https://github.com/hqarroum/the-pointer-arithmetics-challenge
πββοΈ Retrieving a pointer to a structure given a pointer to one of its member.
https://github.com/hqarroum/the-pointer-arithmetics-challenge
c pointer-arithmetics
Last synced: about 1 year ago
JSON representation
πββοΈ Retrieving a pointer to a structure given a pointer to one of its member.
- Host: GitHub
- URL: https://github.com/hqarroum/the-pointer-arithmetics-challenge
- Owner: HQarroum
- Created: 2021-08-03T09:32:37.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2021-08-03T22:21:15.000Z (almost 5 years ago)
- Last Synced: 2025-02-02T08:17:42.465Z (over 1 year ago)
- Topics: c, pointer-arithmetics
- Language: C
- Homepage:
- Size: 2.85 MB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
The Pointer Arithmetics Challenge
A byte-sized C coding brain teaser.
## π The Challenge
> I participated to a programming contest a few years ago, and came across an interesting challenge related to pointer arithmetic in C. I decided to create a write-up on the subject to expose the problem and the proposed solution.
The goal of the challenge is to retrieve the pointer to a structure given a pointer to one of its member. The challenge must be done independently of the number of members in the structure, the size of the structure, or the compiler which can vary during the test of implementation.
For the purpose of the challenge, we will consider the following structure of type `t_struct` which holds a float, an int (our member, aptly named member) and a charΒ :
```c
typedef struct {
float f;
int member;
char c;
} t_struct;
```
We need to provide a function that takes a pointer to a member of a structure and returns a pointer to the actual structure. The function must be prototyped as followΒ :
```c
t_struct* get_struct_ptr(void* member);
```
The `get_struct_ptr` function is expected to be used as in the following example by the testing application provided during the contest.
```c
int main(void) {
t_struct test = {
.f = 1.0,
.member = 42,
.c = 0x42
};
t_struct* ptr = get_struct_ptr(&test.member);
return (ptr == &test ? EXIT_SUCCESS : EXIT_FAILURE);
}
```
## π‘ The Solution
> For a full explanation of the solution, please see the [deep-dive article on Medium](https://medium.com/@HalimQarroum/the-pointer-arithmetics-challenge-42c5a8d58314).
This repository contains a working solution that should be working with all ANSI/C compilers. It currently has been tested on `GCC 10` and `Clang 12`.
## π See also
- The [`offsetof()`](http://en.wikipedia.org/wiki/Offsetof) macro.
- The [deep-dive article on Medium](https://medium.com/@HalimQarroum/the-pointer-arithmetics-challenge-42c5a8d58314).