[英]implementation of sizeof operator in C
我試圖實現這個問題中給出的內容。 實施規模
#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;
}
但是,當我編譯時,出現以下錯誤。
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))
^
((char*)(&int + 1)-(char*)(&int))
您的宏正在嘗試獲取類型的地址。 您可以通過在其中包含一個帶有局部變量的整個塊來使宏更長(但是宏將無法按您想要的方式工作),或者僅在變量而不是類型上使用宏。
這適用於類型,但不適用於變量:
#define tsizeof(type) (((char *)(1+((type *)0))) - ((char *)((type *)0)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.