C基础:结构体

转载请注明出处:http://blog.csdn.net/droyon/article/details/9823093

结构体定义:

struct complex_struct { 
double x, y; 
} z1, z2; 

声明变量:
struct complex_struct z3, z4; 
或:
complex_struct z1 = { x, 4.0, }; /* z1.x=3.0, z1.y=4.0 */ 
complex_struct z2 = { 3.0, }; /* z2.x=3.0, z2.y=0.0 */ 
complex_struct z3 = { }; /* z3.x=0.0, z3.y=0.0 */ 

1、测试例子:结构体的初始化

#include <stdio.h>
int main(void){
    struct HELLO_WORLD {
        long x,y;
    } myX1,myX2;

    struct HELLO_WORK{
        int m;
        long n;
    };

    struct HELLO_WORK myM1 = {1,2.0,};//参数后面可以多个“,”号
    struct HELLO_WORK myM2 = {};//使用0去初始化
    struct HELLO_WORK myM3 = {3};//单个参数初始化,第二个用0

    //myX1 = {4.5,5.6};

    myX2.x = 6.7;
    myX2.y = 7.8;

    printf("myX1.x:%ld\t,myX1.y:%ld\t,myX2.x:%ld\t,myX2.y:%ld\t\n",myX1.x,myX1.y,myX2.x,myX2.y);
   
    printf("myM1.m:%d\t,myM1.n:%ld\t,myM2.m:%d\t,myM2.n:%ld\t,myM3.m:%d\t,myM3.n:%ld\t\n",myM1.m,myM1.n,myM2.m,myM2.n,myM3.m,myM3.n);
    
    return 0;
}

打印:

myX1.x:0	,myX1.y:4195344	,myX2.x:6	,myX2.y:7	 
myM1.m:1	,myM1.n:2	,myM2.m:0	,myM2.n:0	,myM3.m:3	,myM3.n:0

2、测试例子:结构体函数

#include <stdio.h>

struct HELLO_WORLD {
    int x,y;
};

struct HELLO_WORLD addHelloworldStruct(struct HELLO_WORLD struct1,struct HELLO_WORLD struct2){
    struct1.x = struct1.x + struct2.x;
    struct1.y = struct1.y + struct2.y;
    return struct1;
}

int main(void){

    struct HELLO_WORLD x = {1,2};
    struct HELLO_WORLD y = {3,4};

    struct HELLO_WORLD z = addHelloworldStruct(x,y);

    printf("x:%d\t,y:%d\t\n",z.x,z.y);
    return 0;
}

打印:
x:4	,y:6


你可能感兴趣的:(struct,结构体,inuxC)