| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 727 人关注过本帖, 1 人收藏
标题:一个很简单的问题,但我解决不了
只看楼主 加入收藏
uncle_cash
Rank: 1
等 级:新手上路
帖 子:7
专家分:1
注 册:2011-6-4
收藏
得分:0 
用了strcpy函数还是不行,谢谢大家的热心回应,我自己再试试
2011-06-04 22:02
beyondyf
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
等 级:贵宾
威 望:103
帖 子:3282
专家分:12654
注 册:2008-1-21
收藏
得分:0 
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 
struct rating{
     int rating_2011;
     int rating_2012;
};

 
struct school{
     char name[20];
     struct rating rating;
     int school_num;
};

 
int main ()
{
    char a[20];
    int b,c,d;
    struct school no1;
    struct school no2;
    printf("plz enter your school name:\n");
    scanf("%s",a);
    printf("plz enter your school rating in 2011:\n");
    scanf("%d",&b);
    printf("plz enter your school rating in 2012:\n");
    scanf("%d",&c);
    printf("plz enter your school number:\n");
    scanf("%d",&d);
     
    strcpy(no1.name, a);
    no1.rating.rating_2011 = b;
    no1.rating.rating_2012 = c;
    no1.school_num = d;
    no2=no1;
     
    printf("the name of your school is %s\n", no1.name);
    printf("the rating of %s in 2011 is %d\n",no1.name,no1.rating.rating_2011);
    printf("the rating of %s in 2012 is %d\n",no1.name,no1.rating.rating_2012);
    printf("the school number of %s is %d\n", no1.name,no1.school_num);
     
    printf("\n");
     
    printf("the name of your school is %s\n", no2.name);
    printf("the rating of %s in 2011 is %d\n",no2.name,no2.rating.rating_2011);
    printf("the rating of %s in 2012 is %d\n",no2.name,no2.rating.rating_2012);
    printf("the school number of %s is %d\n", no2.name,no2.school_num);
     
    printf("\n");
     
    system("Pause");
    return 0;
}

plz enter your school name:
Tom
plz enter your school rating in 2011:
3
plz enter your school rating in 2012:
2
plz enter your school number:
456
the name of your school is Tom
the rating of Tom in 2011 is 3
the rating of Tom in 2012 is 2
the school number of Tom is 456

the name of your school is Tom
the rating of Tom in 2011 is 3
the rating of Tom in 2012 is 2
the school number of Tom is 456

重剑无锋,大巧不工
2011-06-04 23:20
uncle_cash
Rank: 1
等 级:新手上路
帖 子:7
专家分:1
注 册:2011-6-4
收藏
得分:0 
问题解决了,太感谢beyondyf
但有一点不明白,为何把字串内容指派给结构内的成员要用strcpy函数而不可以直接no1.name=a;????
2011-06-05 09:55
beyondyf
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
等 级:贵宾
威 望:103
帖 子:3282
专家分:12654
注 册:2008-1-21
收藏
得分:0 
以下是引用uncle_cash在2011-6-5 09:55:07的发言:

问题解决了,太感谢beyondyf
但有一点不明白,为何把字串内容指派给结构内的成员要用strcpy函数而不可以直接no1.name=a;????

你的结构中name是数组,虽然其名称相当于指针,但不能改变。你想那么做的话可以将name改成指针类型,但这样做存在安全风险,其它代码对a的改变将直接反应到name上,并且当a的生存期结束后name将成为悬空指针。一种更好的方案是用malloc从堆中动态申请内存分配给name而不是将栈内的内存分配给name。你代码中的a是栈内的一块内存。

重剑无锋,大巧不工
2011-06-05 10:56
快速回复:一个很简单的问题,但我解决不了
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018260 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved