Skip to content

Instantly share code, notes, and snippets.

@copenhas
Created November 5, 2010 12:27
Show Gist options
  • Save copenhas/664062 to your computer and use it in GitHub Desktop.
Save copenhas/664062 to your computer and use it in GitHub Desktop.
C Macro that effectively does hierarchical type casting. Credit goes out to an unknown Linux kernel developer.
/*
* Name: container_of
* Parameters: ptr - Pointer to the inner structure that you have.
* Parameters: type - The type of outer structure you want to have.
* Parameters: member - The member in the outer structure for the inner.
* Returns: type * - Pointer to the outer structure you wanted.
* Description:
* This is a macro used to get to a child structure when you have a pointer
* to the root structure. Notice that this makes no checks or validation.
* Use when you know what you have and what you want.
*/
#define container_of(ptr, type, member)({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type, member) ); \
})
@tgbssk
Copy link

tgbssk commented Oct 28, 2023

// I have one structure and enum
enum { VAR_NONE, VAR_FLOAT, VAR_ARRAY, VAR_STRING };

typedef struct Struct_K
{
int type;
union
{
float val;
float *array;
char string;
};
}Struct_K;
// Then
#define AFA(value) (Struct_K){.type = VAR_ARRAY, .array = (float
) value}
// Then
float myArray[] = {1.0f, 2.0f, 3.0f};
// So can AFA macro directly typecast myArray for Struct_K type ?
// And can I use AFA(myArray) directly to pass as parameter that accepts Struct_K type parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment