结构体题如下

来源:百度知道 编辑:UC知道 时间:2024/05/25 20:57:48
结构体类型定义如下:
typedef struct {
char cLevel ;
uchar ucScale ;
ushort usCategoryCode ;
uchar ucAttribute ;
} Category_t ;
使用上面的结构体类型定义,在程序中完成下列要求:
• 在Main函数中定义一个结构体指针,申请一块结构体类型大小的内存块,使该结构体指针指向该内存块的首地址;
• 申请内存的功能通过函数调用完成,利用返回值判断是否申请内存成功,如果失败,请打印“Allocate Memory Failed!”,如果成功,则赋初值;
• 打印功能通过函数调用完成。

#include "stdio.h"
#include "string.h"
#include <stdlib.h>
typedef unsigned char uchar;
typedef unsigned short ushort;

typedef struct {
char cLevel;
uchar ucScale;
ushort usCategoryCode;
uchar ucAttribute;
} Category_t ;
Category_t * newCT()
{
return (Category_t *)malloc(sizeof(Category_t));
}
void print(Category_t *p)
{
printf("%c %c %c %d\n",p->cLevel,p->ucAttribute,p->ucScale,p->usCategoryCode);
}
int main()
{
Category_t *p;
p=newCT();
if(p==NULL)
{
printf("Allocate Memory Failed!\n");
return 0;
}
else{
p->cLevel='A';
p->ucScale='B';
p->ucAttribute='C';
p->usCategoryCode=1;
}
print(p);

return 0;
}