struct_array.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct MyData {
int len;
char data[10];
} MyData_t;
struct MyData2 {
int len;
char data[];
} MyData2_t;
struct stu {
int age;
char name[32];
//char *name;
};
struct data {
int len;
//struct MyData d[0];
struct stu stu[];
} data_t;
int main()
{
struct MyData d1;
struct MyData2 *d2;
struct data *d3 = NULL;
printf("test struct and array size. \n");
printf("struct size:%d, no array:%d \n", sizeof(struct MyData), sizeof(struct MyData2));
d1.len = 14;
memcpy(d1.data, "123456789", 10);
printf("d1 size:%d, data:%s\n", d1.len, d1.data);
printf("==========1. ===========\n");
d2 = (struct Mydata2 *)malloc(sizeof(int) + 10);
d2->len = sizeof(int) + 10;
memcpy(d2->data, "abcdefghi", 10);
printf("d2 size:%d, data:%s\n", d2->len, d2->data);
free(d2);
printf("==========2. ===========\n");
printf("array: %d\n", sizeof(struct data));
printf("=========3. ============\n");
d3 = (struct data *)malloc(sizeof(int) + sizeof(struct stu));
d3->len = sizeof(int) + sizeof(struct stu) + 32;
d3->stu[0].age = 18;
//d3->stu[0].name = (char *)malloc(32);
memcpy(d3->stu[0].name, "dilireba", sizeof(d3->stu[0].name));
printf("data len:%d, stu age:%d, name:%s\n", d3->len, d3->stu[0].age, d3->stu[0].name);
//free(d3->stu[0].name);
free(d3);
return 0;
}
编译:
gcc struct_array.c
输出:
test struct and array size.
struct size:16, no array:4
d1 size:14, data:123456789
==========1. ===========
d2 size:14, data:abcdefghi
==========2. ===========
array: 4
=========3. ============
data len:72, stu age:18, name:dilireba