结构体与函数

作者在 2011-09-13 12:33:27 发布以下内容
# include <stdio.h>
# include <string.h>        //使用strcpy函数,需要使用string.h头文件

struct Student
{
    int age;
    char sex;
    char name[100];        //定义字符串类型
};

int main(void)
{
    struct Student st;

    st.age = 18;
    st.sex = 'F';
    strcpy(st.name,"张三");        //用字符串赋值,需要用到字符串拷贝函数strcpy,strcpy是string+copy的缩写

    printf("%d %c %s\n",st.age,st.sex,st.name);        
    
    return 0;
}

/*
在VC++6.0中的输出结果为:
————————————
18 F 张三
Press any key to continue
————————————
*/

尝试用函数替代主函数里赋值的语句,但这么写是错误的

# include <stdio.h>
# include <string.h>        

struct Student
{
    int age;
    char sex;
    char name[100];        
};

void InputStudent (struct Student s)    //函数中改变形参s中成员的值,不会改变主函数中st的成员的值
{
    s.age = 18;
    s.sex = 'F';
    strcpy(s.name,"张三");    
}

int main(void)
{
    struct Student st;
    
    InputStudent (st);        //这样调用函数,目的,没有给st的成员赋值,st里面都是垃圾值

    printf("%d %c %s\n",st.age,st.sex,st.name);        
    
    return 0;
}

/*
在VC++6.0中的输出结果为:
————————————
-858993460 ?烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫汤

这里,正确使用函数为结构体各成员赋值的方法是

# include <stdio.h>
# include <string.h>        

struct Student
{
    int age;
    char sex;
    char name[100];        
};

void InputStudent (struct Student * s)    //s是&st的拷贝,所以数据类型应该是struct Student * 型
{
    s->age = 18;        //s->age 相当于(*s).age 所以就相当于 st.age
    s->sex = 'F';
    strcpy(s->name,"张三");    
}

int main(void)
{
    struct Student st;
    
    InputStudent (&st);        //要想通过函数改变变量值,函数的实参必须是地址

    printf("%d %c %s\n",st.age,st.sex,st.name);        
    
    return 0;
}

/*
在VC++6.0中的输出结果为:
————————————
18 F 张三
Press any key to continue
————————————
*/

当然,也可以用函数来对结构体成员进行输出,注意这个函数是发送内容好,还是发送地址好

# include <stdio.h>
# include <string.h>        

struct Student
{
    int age;
    char sex;
    char name[100];        
};

void OutputStudent (struct Student s)
{
    printf("%d %c %s\n",s.age,s.sex,s.name);    //OutputStudent函数只执行printf的功能,不涉及修改主函数中的值
}

void OutputStudent2 (struct Student * s)
{
    printf("%d %c %s\n",s->age,s->sex,s->name);    
}

void InputStudent (struct Student * s)    
{
    s->age = 18;        
    s->sex = 'F';
    strcpy(s->name,"张三");    
}

int main(void)
{
    struct Student st;
    
    InputStudent (&st);        
    OutputStudent (st);            //所以,这里实参不必使用地址变量
                                
//但这样一来,发送的数据将是结构体所占的空间,即108个字节
                                
//占用内存大,速度也慢
    OutputStudent2 (&st);        //所以还是推荐使用地址,此时,发送的数据仅是指针变量所占的空间,即4个字节
    
    return 0;
}

/*
在VC++6.0中的输出结果为:
————————————
18 F 张三
18 F 张三
Press any key to continue
————————————
*/
郝斌视频笔记 | 阅读 1131 次
文章评论,共0条
游客请输入验证码
最新评论