-3

I tried to implement what is given in this question.sizeof implementation

#include <stdio.h>
#include <stdint.h>

#define my_sizeof(type) ((char*)(&type + 1)-(char*)(&type))

int main()
{
    printf("Size of int   %d \n",my_sizeof(int));

    return 0;
}

However when I compile I get the following error.

test.c:10:44: error: expected expression before ‘int’
     printf("Size of int   %d \n",my_sizeof(int));
                                            ^
test.c:5:35: note: in definition of macro ‘my_sizeof’
 #define my_sizeof(type) ((char*)(&type + 1)-(char*)(&type))
                                   ^
test.c:10:44: error: expected expression before ‘int’
     printf("Size of int   %d \n",my_sizeof(int));
                                            ^
test.c:5:54: note: in definition of macro ‘my_sizeof’
 #define my_sizeof(type) ((char*)(&type + 1)-(char*)(&type))
                                                      ^
Community
  • 1
  • 1
liv2hak
  • 14,472
  • 53
  • 157
  • 270

2 Answers2

3
((char*)(&int + 1)-(char*)(&int))

Your macro is trying to take the address of a type. You could either make the macro a lot longer by including a whole block in it with a local variable (but then the macro wouldn't work how you want) or just only use the macro on variables and not types.

Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36
2

This works for types, but not for variables:

#define tsizeof(type) (((char *)(1+((type *)0))) - ((char *)((type *)0)))
rcgldr
  • 27,407
  • 3
  • 36
  • 61