码迷,mamicode.com
首页 > 编程语言 > 详细

C语言之结构体

时间:2014-08-19 11:10:04      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:c结构体

1 概述

    结构体就是一个可以包含不同数据类型的一个结构,它是一种可以自己定义的数据类型。

2 定义结构体类型变量的方法

 定义结构体变量的一般格式为:

    struct 结构名

    {

        类型  变量名;

        类型  变量名;


        ...

    }结构变量;

    代码如下:

struct Student{
        char name[8];
        int age;
    }stu1;

    上面的代码声明了一个名为Student的结构体,它包含两个成员name和age,成员name的数据类型为字符数组,成员age的数据类型位整形,同时定义了一个Student结构体变量stu1.

注意:结构体声明的时候本身不占用任何内存空间,只有当定义结构体变量的时候计算机才会分配内存。

也可以通过 struct Student 结构体变量名; 方式定义结构体变量,代码如下:

struct Student stu2 = {"Lily",19};

还可以通过typedef 形式简化,代码如下:

typedef struct Student MyStudent;
MyStudent stu3 = {"Jake",20};

完整例子如下:

#include <CoreFoundation/CoreFoundation.h>

int main(int argc, const char * argv[])
{

    struct Student{
        char name[8];
        int age;
    }stu1;
    
    typedef struct Student MyStudent;
    
    strcpy(stu1.name, "Jackz");
    stu1.age = 20;
    printf("姓名:%s,年龄:%d\n",stu1.name,stu1.age);
    
    struct Student stu2 = {"Lily",19};
    printf("姓名:%s,年龄:%d\n",stu2.name,stu2.age);
    
    MyStudent stu3 = {"Jake",20};
    printf("姓名:%s,年龄:%d\n",stu3.name,stu3.age);
    return 0;
}

结果如下图:

bubuko.com,布布扣

引申:链表的简单使用

#include <CoreFoundation/CoreFoundation.h>

int main(int argc, const char * argv[])
{
    typedef struct _Node{
        float score;
        int age;
        struct _Node *next;
    }Node;
    Node node1,node2,node3;
    node1.score = 60.5;
    node1.age = 18;
    node2.score = 80.4;
    node2.age = 19;
    node3.score = 100.2;
    node3.age = 20;
    
    node1.next = &node2;
    node2.next = &node3;
    node3.next = 0;
    
    Node curNode = node1;
    printf("分数:%.1f,年龄:%d\n",curNode.score,curNode.age);
    do {
        curNode = *curNode.next;
        printf("分数:%.1f,年龄:%d\n",curNode.score,curNode.age);
    }while (curNode.next);
    
    return 0;
}

结果如下:

bubuko.com,布布扣

本文出自 “7803002” 博客,请务必保留此出处http://7813002.blog.51cto.com/7803002/1541817

C语言之结构体,布布扣,bubuko.com

C语言之结构体

标签:c结构体

原文地址:http://7813002.blog.51cto.com/7803002/1541817

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!