C99_變長結構體實現,c99結構體實現
/************************************************************************* > File Name: C99_lengthenStruct.c > Author: zshh0604 > Mail: zshh0604@163.com > Created Time: 2014年10月16日 星期四 17時19分35秒 ************************************************************************/#include<stdio.h>#include<stdlib.h>#include<string.h>/*** * C99中變成結構的實現。 * * 一:變長結構體實現的兩個原理。 *1.結構體的地址空間是連續的。 *2.數組的地址空間也是連續的。 * *二: 變長結構體的表示方法如下。 * 1.typedef struct *{ *int data1; *char data2[20]; *int data3[0]; *} data; *2.其中data3[0]必須是在結構體的最後的一個元素。 *三: *Demo說明如何進行資料存取。 * *//** * 用來測試變長結構體的資料結構。 */typedef struct {int data1;char data2[20];int data3[0];}data;/*** * 測試將結構體存放到可變結構體中 */typedef struct{int data1;char data2[30];char data3[0];}datas;/* *測試將people結構體存放到datas中。 */typedef struct{int id;char name[30];}people;/*** * 初始可變長結構體。 */void init_data(void){data * d = NULL; int i = 0;d = malloc(sizeof(data)+sizeof(int)*30);if(d== NULL){printf("分配地址空間失敗\n");return;}d->data1 = 10;strncpy(d->data2,"hello world",strlen("hello world")+1);for(i=0;i<30; i++){ d->data3[i] = i;printf("d->data3[%d] = %d\n",i,d->data3[i]);}}void init_datas(void){datas * d = NULL;people p;people *p1;d = malloc(sizeof(datas) + sizeof(people));p.id = 10;strncpy(p.name,"gameone",strlen("gameone")+1);memcpy(d->data3,&p,sizeof(people));p1 = (people*) d->data3;printf("p1.id = %d\n", p1->id);printf("p1.name = %s\n", p1->name);return;}void main(void){init_data();init_datas();}轉載請註明出處http://blog.csdn.net/shaohuazuo/article/details/40159531
變長結構體套變長結構體怎使用
什麼是變長?char b[1];
struct a
{
int a;
char b[1];
};
struct b
{
int a;
struct a c[1];
};
int main()
{
printf("strlen is %d,strlen b is %d\n",sizeof(struct a),sizeof(struct b));
return 0;
}
長度都是固定的,如果不按照位元組對齊 a的大小是8,b是12
如果#pragma pack(1)
則a的大小是5,b是9
c語言結構體中定義變長資料:
struct temp{
int a;
char *b;
short c;
char d;
char *f;
};