试图打印一个struct元素但是变成空白。 - C

时间:2015-02-21 19:22:21

标签: c string printing struct format

我有一个struct person,其中包含data.h

中定义的以下元素
typedef struct person{
    char firstName[20];
    char familyName[20];
    char telephoneNum[20];
    int type; // 0 = student / 1 = employee;
}newPerson;

我创建了一个person[MAX_PERSONS]数组,该数组在我的menu()函数中初始化。然后我有一个addFirstName(newPerson pers)函数。但是,当我尝试使用printFormat(newPerson pers)函数测试打印格式时,我得到空白,而不是输入的名称。

我在下面添加了menu(),addFirstname(newPerson pers)和printFormat(newPerson pers)函数。我想知道是否有人能告诉我这个的原因。任何帮助或指示将不胜感激。提前谢谢。

int menu(){
    int num = 0;
    newPerson person[MAX_PERSONS]; 
    int option; // for user input for menu
    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]);
        printFormat(person[num]);
        char choice[0];
        printf("\n\t\tWould you like to enter another record? (y/n): ");
        scanf("%s", choice);    
        if (choice[0] == 'y'){
            num++;
            addRecord(person[num]);

        }
        if (choice[0] == 'n'){
            num++;
            mainMenu();
        }               
            /*

            IF YES, THEN NUM++
            THEN RUN ADDRECORD(PERSONNUM) AGAIN.    

            IF NO, THEN RETURN TO MAIN MENU.
            PRINTMENU
            THEN RUN MENU AGAIN
        */  
    }

    printf("\n\tNot a valid option, please try again // THE END OF MENU FUNCTION\n");
    return 0;
}

void addFirstName(newPerson pers){
    char firstName[20];
    printf("\n\tEnter first Name: ");
    scanf("%20s", firstName);
    strcpy(pers.firstName, firstName);
    printf("\n\tThe name entered is %s", pers.firstName);
}


void printFormat(newPerson pers){
    printf("\t\tThe name is %s", pers.firstName);
}

2 个答案:

答案 0 :(得分:4)

这是因为您通过值将结构传递给addFirstName ,这意味着该函数接收结构的副本。而更改副本当然不会改变原件。

虽然C不支持通过引用传递参数,但可以使用指针进行模拟。因此,将addFirstName函数更改为接收指针作为参数。

答案 1 :(得分:0)

你的大问题是你是按值而不是通过指针传递结构。这导致您更改函数addFirstName内的原始对象的副本,而不是原始对象。你应该声明为:

void addFirstName( newPerson* pers);
void printFormat( newPerson* pers);

示例:

#include <stdio.h>

void call_by_value(int x) {
    printf("Inside call_by_value x = %d before adding 10.\n", x);
    x += 10;
    printf("Inside call_by_value x = %d after adding 10.\n", x);
}

int main() {
    int a=10;

    printf("a = %d before function call_by_value.\n", a);
    call_by_value(a);
    printf("a = %d after function call_by_value.\n", a);
    return 0;
}

这会产生:

a = 10 before function call_by_value.
Inside call_by_value x = 10 before adding 10.
Inside call_by_value x = 20 after adding 10.
a = 10 after function call_by_value.