Domanda

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

int main(void)
{
   int answer;
   short x = 1;
   long y = 2;
   float u = 3.0;
   double v = 4.4;
   long double w = 5.54;
   char c = 'p';

   uint32_t e = 653;
   uint16_t f = 44;
   uint64_t g = 2323232;


   typedef enum
   {
      kCountInvalid,
      kCountOne,
      kCountTwo,
      kCountThree,
      kCountFour,
   }k_count_t;

  /* __DATE__, __TIME__, __FILE__, __LINE__ are predefined symbols */
  #if 1
  printf("Date : %s\n", __DATE__);
  printf("Time : %s\n", __TIME__);
  printf("File : %s\n", __FILE__);
  printf("Line : %d\n", __LINE__);
  #endif

  /* The size of various types */
  printf("The size of int             %zu\n", my_sizeof_one(answer));
  printf("The size of short           %zu\n", my_sizeof_one(x));
  printf("The size of long            %zu\n", my_sizeof_one(y));
  printf("The size of float           %zu\n", my_sizeof_one(u));
  printf("The size of double          %zu\n", my_sizeof_one(v));
  printf("The size of long double     %zu\n", my_sizeof_one(w));
  printf("The size of char            %zu\n", my_sizeof_one(c));
  printf("The size of enum            %zu\n", my_sizeof_one(k_count_t));

  printf("The size of uint16_t        %zu\n", my_sizeof_one(f));
  printf("The size of uint32_t        %zu\n", my_sizeof_one(e));
  printf("The size of uint64_t        %zu\n", my_sizeof_one(g));

  return 0;
}

I get the following error:

 error: expected expression before 'k_count_t'
 error: expected expression before 'k_count_t'

For some reason my_sizeof doesn't seem to work for enumerated data type in C.Can someone explain the reason for this?

È stato utile?

Soluzione

The problem is that you are passing a type to your macro, and the macro does not work for types. Because you cannot take the address of a type.

Although you've named the parameter of your macro type, that name is misleading. The macro accepts variables rather than types. Well, strictly it accepts anything for which you can take the address using the & operator. Notice that all your other uses of the macro are with variables. Supply a variable of type k_count_t to your macro and the compiler will be happy.

Of course, the real lesson to learn is to use sizeof like nature intended.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top