C-将指向数组的指针传递给函数以打印该数组

时间:2018-06-27 04:01:39

标签: c arrays pointers

我有一个用于学生管理系统的代码。输入函数工作正常,但我还没有弄清楚为什么我调用输出函数时会立即停止。(我知道我无法从C函数返回本地数组,但是我将数组分配给指针并返回那个指针,可以吗?)

这是我的代码:

 struct Student
{

    char name[50];
    char birth[25];
    char gender[10];
    float math, physics;

};

struct Student* input(int n, struct Student *p)
{
    int i, id = 1;

    struct Student s[n];

    getchar();

    for(i = 0; i < n; i++)
    {


        printf("Name: ");
        fgets(s[i].name, 50, stdin);
        s[i].name[strlen(s[i].name)-1] = '\0';

        printf("Date of birth: ");
        fgets(s[i].birth,25,stdin);
        s[i].birth[strlen(s[i].birth)-1] = '\0';

        printf("Gender: ");
        fgets(s[i].gender,10,stdin);
        s[i].gender[strlen(s[i].gender)-1] = '\0';

        printf("Math = ");
        scanf("%f", &s[i].math);

        printf("Physics = ");
        scanf("%f", &s[i].physics);

        getchar();
    }
    p = s;
return p;
}


void outPut(int n, struct Student *p)
{   
    int i;
    for(i = 0; i < n; i++)
    {
        printf("%s %s %s %f %f\n",  p[i].name, p[i].birth, p[i].gender, p[i].math, p[i].physics);
    }
}


int main()
{
    int n;

    struct Student *p, *p1;
    int choice;

    printf("-----------Student Management-----------");
    printf("\n1. Add new students.\n2. Print student list.\n");

    do
    {
        printf("Your choice = ");
        scanf("%d", &choice);
        switch(choice)
        {
            case 1:
                printf("Number of students = ");
                scanf("%d", &n);
                input(n,p);
                break;

            case 2:
                outPut(n,p);
                break;

        }
    }
    while(choice!=0);
return 0;
}

1 个答案:

答案 0 :(得分:1)

您正在将数组定义为局部变量。这意味着该函数结束后将不再存在。为避免这种情况,请将您的数组声明为指针,并使用 malloc 对其进行初始化:

 print 'Enter the number of lists and mod value:'
    a, b = map(int, sys.stdin.readline().split())
    lst = []
    for i in range(a):
        v = []
        v = raw_input()
        lst.append(v)
    print lst

它将像常规数组一样工作,您将可以将其自身用作函数返回。