From these question: Casting one struct pointer to another - C, I would like to know, if it is possible to use a member of a "general" struct typed to a "specific" struct:
#include <stdio.h>
#include <stdlib.h>
enum type_e { CONS, ATOM, FUNC, LAMBDA };
typedef struct {
enum type_e type;
} object;
typedef struct {
enum type_e type;
char *expression;
} lambda_object;
typedef struct {
enum type_e type;
object *car, *bus;
int value;
} cons_object;
object *traverse(object *o){
if (o->type == CONS){
cons_object *cons = (cons_object*)o;
traverse(cons->car);
traverse(cons->bus);
return (object*)cons;
} else if (o->type == LAMBDA) {
lambda_object *lam = (lambda_object*)o;
return (object*)lam;
}
return 0;
}
int main(){
lambda_object l = {LAMBDA, "value to print\n"};
object *p = traverse((object*)&l);
printf("sizeof(object):%lu\nsizeof(lambda_object):%lu\n",sizeof(object), sizeof(lambda_object));
printf("%s\n",*(p+4));
}
Which emits no error, just command terminated
so I have no idea what gone wrong, but suspect I tried to deference wrong address *(p+4)
, but I know, there is a pointer to my string. From definition of lambda_object
, after enum
(which is 4 bytes long, just as int
), there is my pointer. So I should not be dereferencing wrong address, but still I cannot. Why?
output:
a.c: In function ‘main’:
a.c:46:11: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘object’ {aka ‘struct <anonymous>’} [-Wformat=]
printf("%s\n",*(p+4));
~^ ~~~~~~
Press ENTER or type command to continue
sizeof(object):4
sizeof(lambda_object):16
Command terminated
EDIT:
I have tried (char*)p[4]
, still termination