Latest web development tutorials

C libreria di macro - offsetof ()

C libreria standard - <stddef.h> C libreria standard - <stddef.h>

descrizione

C libreria di macrooffsetof (tipo, membro-designatore) genera una costante tipo intero size_t,che è un elemento strutturale della struttura relativa allo spostamento di byte dall'inizio. Gli dagli Stati-designatore data, in nome del tipo di struttura è dato.

dichiarazione

Ecco offsetof () dichiarazione macro.

offsetof(type, member-designator)

parametri

  • Tipo - questo è un tipo di classe, in cui, membro-designatore è un membro valida dell'indicatore.
  • membro-designatore - che è un membro di un indicatore di tipo di classe.

Valore di ritorno

Questa macro restituisce un valore di tiposize_t, mostrando il tipo di offset di membri.

Esempi

L'esempio seguente mostra offsetof () l'utilizzo di macro.

#include <stddef.h>
#include <stdio.h>

struct address {
   char name[50];
   char street[50];
   int phone;
};
   
int main()
{
   printf("address 结构中的 name 偏移 = %d 字节。\n",
   offsetof(struct address, name));
   
   printf("address 结构中的 street 偏移 = %d 字节。\n",
   offsetof(struct address, street));
   
   printf("address 结构中的 phone 偏移 = %d 字节。\n",
   offsetof(struct address, phone));

   return(0);
} 

Facciamo compilare ed eseguire il programma di cui sopra, che si tradurrà in quanto segue:

address 结构中的 name 偏移 = 0 字节。
address 结构中的 street 偏移 = 50 字节。
address 结构中的 phone 偏移 = 100 字节。

C libreria standard - <stddef.h> C libreria standard - <stddef.h>