lz_zt 2020-03-19 00:10 采纳率: 33.3%
浏览 130
已采纳

指针不匹配,指针冲突

在写结构体的时候,我发现了这样的一个现象

#include<stdio.h>

int prt(struct student *stu);

struct student
{
    char *name;
    float score[3];
};



int main()
{

    struct student stu;
    stu.name = "cxk";
    stu.score[0] = 98.5;
    stu.score[1] = 97.5;
    stu.score[2] = 99.5;
    prt( &stu );
}

int prt(struct student *stu)
{
    printf("name : %s\n",stu -> name);
    printf("socre[0] : %f\n",stu -> score[0]);
    printf("socre[1] : %f\n",stu -> score[1]);
    printf("socre[2] : %f\n",stu -> score[2]);
}

这样写会有报错图片说明
指针不兼容,冲突。
我在网上搜了半天没搞懂这是为什么
但如果将函数声明放在main函数中

#include<stdio.h>


struct student
{
    char *name;
    float score[3];
};



int main()
{
    int prt(struct student *stu);
    struct student stu;
    stu.name = "cxk";
    stu.score[0] = 98.5;
    stu.score[1] = 97.5;
    stu.score[2] = 99.5;
    prt( &stu );
}

int prt(struct student *stu)
{
    printf("name : %s\n",stu -> name);
    printf("socre[0] : %f\n",stu -> score[0]);
    printf("socre[1] : %f\n",stu -> score[1]);
    printf("socre[2] : %f\n",stu -> score[2]);
}

就没有错误,希望有大神可以指点一下

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-03-19 09:38
    关注

    C语言要求先定义后使用
    int prt(struct student *stu);
    要放在
    struct student
    定义后面。

    以下2个写法都可以

    #include<stdio.h>
    struct student
    {
        char *name;
        float score[3];
    };
    
    int prt(struct student *stu);
    
    int main()
    {
    
        struct student stu;
        stu.name = "cxk";
        stu.score[0] = 98.5;
        stu.score[1] = 97.5;
        stu.score[2] = 99.5;
        prt( &stu );
    }
    
    int prt(struct student *stu)
    {
        printf("name : %s\n",stu -> name);
        printf("socre[0] : %f\n",stu -> score[0]);
        printf("socre[1] : %f\n",stu -> score[1]);
        printf("socre[2] : %f\n",stu -> score[2]);
        return 0;
    }
    
    
    #include<stdio.h>
    
    struct student;
    int prt(struct student *stu);
    
    struct student
    {
        char *name;
        float score[3];
    };
    
    int main()
    {
    
        struct student stu;
        stu.name = "cxk";
        stu.score[0] = 98.5;
        stu.score[1] = 97.5;
        stu.score[2] = 99.5;
        prt( &stu );
    }
    
    int prt(struct student *stu)
    {
        printf("name : %s\n",stu -> name);
        printf("socre[0] : %f\n",stu -> score[0]);
        printf("socre[1] : %f\n",stu -> score[1]);
        printf("socre[2] : %f\n",stu -> score[2]);
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿