Question

Can somebody explain as simple as you can how what/how *(int*) a works?

As well as how in another file: (any.h)

#ifndef ANY_H
#define ANY_H

typedef void * any;

#endif

Code here is in another file test.c where any.h is included

int abcd(any j) {
   k = ((struct a*)j)->b[0]; 
}

works? For the struct one does it mean, j is the pointer? A little confused.

Was it helpful?

Solution

*(int*)a should give you the contents of the location pointed to by a, while treating a as if it was a pointer to an integer. If a was already a pointer to an integer, *(int*)a is equivalent to *a. The stuff in the brackets is a cast operator.

any is now the equivalent of void *, or a generic pointer that does not refer to any specific value type. void * is normally used for places where you don't want to specify what a pointer is pointing to, but just identify a location in memory (with no regard to its contents). To get the value pointed to by a void pointer, you first need to cast it into a pointer to a specific type, which is what (struct a*)j does: treats j as if it was a pointer to struct a.

OTHER TIPS

When you type (int*) etc it is a cast. This tells the compiler to 'think' of whatever is there as that type.

Hence you are casting (telling the compiler) that j is a pointer to some struct a in the line ((struct a*)j)

Might just add that if j isn't this type you may have strange errors runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top