指向字符串/结构元素的麻烦。厕所

时间:2015-02-22 04:07:06

标签: c pointers struct reference

对不起,如果我的问题不清楚,那么当涉及到c和指针等时,我的词汇量并不是很好。

我有一个简单的程序,它带有一个包含以下结构的标题data.h

#ifndef MENU_H_
#define MENU_H_

typedef struct student{
    int gpa;
    float tuitionFees;
    int numCourses;
}student;

typedef struct employee{
    float salary;
    int serviceYears;
    int level;
}employee;

typedef struct person{
    char *firstName[20];
    char familyName[20];
    char telephoneNum[20];
    int type; // 0 = student / 1 = employee;
    union{
        employee e;
        student s;
    };
}newPerson;


#endif /* MENU_H_ */

我有一个main.c,但到目前为止只包含

#include <stdio.h>
#include "menu.h"
#include "data.h"

    main(){

        //printMenu();
        menu();
    }

然后大部分代码都在这里,menu.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "menu.h"
#include "data.h"
#include "uni_personal.h"

int menu(){
    int num = 0;
    newPerson person[MAX_PERSONS];
    int option;
    printf("\n\tPlease choose one of the following options to continue (0-9): ");
    scanf("%d", &option );
    printf("\n\tYou selected %d\n", option);

    if (option == 0){                               //program will close
            printf("\tProgram will now close.\n");
            exit(1);
        }

    if (option == 1){ //program will ask for name input
        addRecord(&person[num], &num);
        printf("\n\tThe name is: %s", *person[num].firstName);
        printf("\n\tThe number is suppose to be 99 if done right == %d\n", person[num].type);
    }
}

void addRecord(newPerson *pers, int *num){
    setStudent(pers, 0);
    addName(pers, num);
}

void addName(newPerson *pers, int *num){
    printf("\tEnter Name: ");
    scanf("%20s", *pers->firstName);
}

void setStudent(newPerson *pers, int *num){
    pers->type = 99; // Test number to see if pointed correctly
}

int changeNum(int *num){
    *num = 50;
    return *num;
}



void printMenu(){
    printf("\n\n\n============================================================\n");
    printf("\t STUDENT/EMPLOYEE RECORDS:\n");
    printf("\t\t1. Add a new record\n");
    printf("\t\t2. Print Student List\n");
    printf("\t\t0. Quit\n");
}

基本上我想要一个用于通过scanf向用户询问名称的函数,然后使用输入的字符串,将其设为person.firstName。然而,我使用的方法,当我尝试将其打印出来时,如果我改变&#34;%s&#34;它将返回null。到&#34;%p&#34;在printf中,它将返回nil。

使用相同的方法,我能够成功设置我的int type,但我正在努力弄清楚如何将用户输入字符串附加到我的person.firstName元素中。

有人能指出我做错了什么吗?任何帮助将不胜感激,谢谢你提前!

1 个答案:

答案 0 :(得分:0)

您已将firstName声明为包含20个指针的数组。我怀疑你想要一个20个字符的简单数组。删除该声明中的*(如familyName)。在对firstName的scanf调用中,只需传递缓冲区,所以再次删除&#34; *&#34;。

相关问题