C 重新學習

1.h文件

/*
 * avcodec.h
 *
 *  Created on: Mar 29, 2019
 *      Author: zdy
 */
typedef signed char             int8_t;
typedef short int               int16_t;
typedef int                     int32_t;

typedef unsigned char           uint8_t;
typedef unsigned short int      uint16_t;
typedef unsigned int            uint32_t;

enum COLOR {
    RED, GREEN, BLUE
};
typedef struct Header {
    int srcId;
    int desId;
    enum COLOR color;
}Header;

typedef struct Payload {
    uint8_t *data;
    int len;
    enum COLOR color;
} Payload;

typedef struct PacketData{
    Header header;
    Payload payload;
}PacketData;

Header *initHeader();
Payload *initPayload();

2.c文件

/*
 * avcodec.c
 *
 *  Created on: Mar 29, 2019
 *      Author: zdy
 */
#include"avcodec.h"
Header *initHeader() {
    return (Header *) malloc(sizeof(Header));
}
Payload *initPayload() {

    Payload *payload = (Payload *) malloc(sizeof(Payload));
    payload->data = (uint8_t *) malloc(1024);
    return payload;
}

3.main

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <signal.h>
#include"avcodec.h"

void showHeader(Header he) {
    printf("srcId =%d,desId =%d,size = %d\n", he.srcId, he.desId, sizeof(he)); //輸入和輸出仍然是整形數據,不能輸入字符串。。。
}

void showHeader1(Header *h) {
    printf("srcId =%d,desId =%d\n", h->srcId, h->desId);
}

void showPayload(Payload *p) {
    int len = p->len;
    int i = 0;
    printf("payload=");
    for (i = 0; i < len; i++) {
        printf("%d ", p->data[i*sizeof(uint8_t)]);
    }
    printf("\n");

}

int main() {
    Header header;
    header.srcId = 20;
    header.desId = 30;
    showHeader(header);

    Header *h = initHeader();
    h->srcId = 21;
    h->desId = 25;
    showHeader1(h);
    //
    printf("payload size =%d\n", sizeof(Payload));
    Payload *p = initPayload();
    uint8_t* datas[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    memcpy(p->data,datas,9*sizeof(uint8_t));
    p->len = 9;
    showPayload(p);
    free(h);
    free(p);
    return 0;
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章