简体   繁体   English

无法从C中的函数返回结构

[英]Can't return a struct from a function in C

Every time i read the employ.sex the program crashes, no errors, i can't find why this is happening. 每次我阅读employee.sex时,程序都会崩溃,没有错误,我找不到发生这种情况的原因。 I'm very new at C. Is something wrong with "return pin[i]? Please help, i can't find anything in my search for it. Thanks in advance 我是C的新人。“回头针[i]出了点问题吗?请帮助,我在搜索中找不到任何内容。在此先感谢您

#include <stdio.h>
#define N 5

struct stoixeia
    {
        int age;
        float h;
        char sex;
    };
struct melos
    {
        char fname[50];
        char lname[50];
        int mnum;
        struct stoixeia employ;
    };

struct melos diavasma(int );

int main()
{
    struct melos pin[N];
    struct melos * ptr;
    int i,pli;
    for(i=0;i<N;i++)
    {
        pin[i]=diavasma(i);
        printf("%d", pin[i].mnum); // i just use this to see if it returns anything
    }
    return 0;
}

struct melos diavasma(int i)
    {
        struct melos pin[i];
        struct stoixeia employ;
        printf("Dose onoma\n");
        scanf("%s", pin[i].fname);
        printf("Dose epitheto\n");
        scanf("%s", pin[i].lname);
        printf("Dose arithmo mitroou\n");
        scanf("%d", &pin[i].mnum);
        printf("Dose ilikia\n");
        scanf("%d", &pin[i].employ.age);
        printf("Dose upsos\n");
        scanf("%f", &pin[i].employ.h);
        printf("Dose fulo\n");
        scanf(" %c", &pin[i].employ.sex);
        return pin[i];
    }

You are close: rather than declaring an array, in which you use a single element past the end, hence the crash, declare a single struct: 您很亲近:不是声明一个数组,而是在数组末尾使用单个元素(因此崩溃),而是声明一个结构:

struct melos diavasma(int i)
{
    struct melos pin;
    printf("Dose onoma\n");
    scanf("%s", pin.fname);
    printf("Dose epitheto\n");
    scanf("%s", pin.lname);
    printf("Dose arithmo mitroou\n");
    scanf("%d", &pin.mnum);
    printf("Dose ilikia\n");
    scanf("%d", &pin.employ.age);
    printf("Dose upsos\n");
    scanf("%f", &pin.employ.h);
    printf("Dose fulo\n");
    scanf(" %c", &pin.employ.sex);
    return pin;
}

Note that passing i is redundant now. 请注意,传递i现在是多余的。 Unless you plan to use it in a prompt, consider removing it from the function's parameter list. 除非打算在提示中使用它,否则请考虑将其从函数的参数列表中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM