使用带结构的指针将数据传递给函数

时间:2014-04-01 19:59:13

标签: c arrays pointers structure

这是一个类项目的程序。假设能够创建和编辑结构。 CreatRec函数工作正常。对于ModifyRec,我试图通过指针发送数组,以避免"复制"数据。但是,我无法让它实际更改阵列。 ATM底部的行(gr [change] .lastname = * info;)根本不起作用。我真的不知道我在这里做错了什么。

 #include "stdafx.h"
#include <string.h>
#include <stdlib.h>

struct student{
    int recordname;
    char lastname[10];
    char firstname[10];
    float math;
    float english;
    float science;
};

//prototypes
int menu();
struct student  CreatRec(int);
void ModifyRec(struct student*);


void main()
{
    int option, j;//option will be for users menu choice, j makes for loop work for creatrec
    struct student grades[10];
    j = 0;
    option=Menu();
    if (option == 1)
        for (j = 0; j<10; j++)
            (grades[j + 0]) = CreatRec(j);
    else if (option==2)
        ModifyRec(grades);//dont need & is smart bc array


    printf("%s",grades[0].lastname);//This line is checking to see if ModifyRec actaully worked

    //free(grades);2
    while (1);
}


int Menu()
{
    int choi;
    printf("Please choose one of the following options.\n 1) Create  New Student Records.\n 2) Modify an Existing Student Record\n");
    printf(" 3) Print a New Sutdent Record.\n 4) Quit\n");
    scanf("%d", &choi);
    return choi;
}
struct student  CreatRec(int i)
{
    struct student qr;
    //qr = (struct student*)malloc(sizeof(struct student)*6);

    printf("RecordNum %i\n", i);
    printf("Please enter last name-->");
    scanf("%s", &qr.lastname);
    printf("Please enter first name-->");
    scanf("%s", &qr.firstname);
    printf("Please math grade-->");
    scanf("%f", &qr.math);
    printf("Please english grade-->");
    scanf("%f", &qr.english);
    printf("Please science grade-->");
    scanf("%f", &qr.science);
    return qr;
}

void ModifyRec(struct student gr[])
{
    int change;
    char feild[10], info[10];

    printf("Which record would you like to change?\n");
    scanf("%d", &change);
    rewind(stdin);
    printf("Which feild would you like to edit?\n");
    scanf("%s", &feild);
    rewind(stdin);
    printf("Enter info\n");
    scanf("%s", &info);

    if (!strcmp("lastname", feild))
        gr[change].lastname= *info;//NOT WORKING

}

2 个答案:

答案 0 :(得分:1)

首先,我在声明

的表达式grades[j + 0]中看不到很有意义
    for (j = 0; j<10; j++)
        (grades[j + 0]) = CreatRec(j);

这些陈述

printf("Please enter last name-->");
scanf("%s", &qr.lastname);
printf("Please enter first name-->");
scanf("%s", &qr.firstname);

必须替换

printf("Please enter last name-->");
scanf("%s", qr.lastname);
printf("Please enter first name-->");
scanf("%s", qr.firstname);

这句话

if (!strcmp("lastname", feild))
    gr[change].lastname= *info;//

必须替换

if (!strcmp("lastname", feild))
    strcpy( gr[change].lastname, info );

答案 1 :(得分:0)

gr[change].lastname是一个char数组,而不是指针。你无法重新分配它。在这种情况下,您可能应该scanf("%s", gr[change].lastname);并完全跳过char info[10]