C/Structure/Struct Size

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Allocate memory for struct

<source lang="cpp">

  1. include <stdlib.h>
  2. include <stdio.h>
  3. include <string.h>

struct address {

 char name[400];
 char street[400];
 char city[400];
 char state[30];
 char zip[100];

}; int main() {

 struct address *p;
 if((p = malloc(sizeof(struct address)))==NULL) {
   printf("Allocation Error\n");
   exit(1);
 }
 return p;

}

      </source>


Get the size of a struct

<source lang="cpp">

  1. include <stdio.h>

struct struct_type {

 int i;
 char ch;
 int *p;
 double d;

} s; int main(void) {

 printf("s_type is %d bytes long", sizeof(struct struct_type));
 return 0;

}


      </source>