C99_變長結構體實現,c99結構體實現

來源:互聯網
上載者:User

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;
};
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.