簡體   English   中英

如何使用數組指針打印結構成員?

[英]how do I print the stuct members using an array pointers?

到目前為止,我編寫的代碼如下所示,沒有庫。 基本上我使用了 stdio.h 和 stdlib.h。

typedef struct ID{
     char firstName[21];
     char lastName[21];
     char phoneNumber[11];
}ID;

ID PrintList(ID *ptr,int i){
     int l=1;
     printf(" #   First Name       Last Name       Phone Number\n");
     while(l<i+1)
     {
        printf(" %d.   %s",l,&ptr[l]);
        l++;
    }
} 

ID addNew(ID *ptr,int i){
    char fname[21],lname[21],phone[11];
    if(i<3)
     {  
        ID user;
        ptr[i] = user;
        printf("enter the first name:   ");
        scanf("%s",&fname);
        *ptr->firstName= fname;
        printf("enter the last name:    ");
        scanf("%s",&lname);
        *ptr->lastName = lname;
        printf("enter the phone number: "); 
        scanf("%s",&phone);
        *ptr->phoneNumber = phone;
    }
    else
    {
        printf("sorry but you have reach max capacity\n");  
    }
} 

int main(int argc, char *argv[]) {
    int answere,i=0;
    printf("******* WELCOME TO PHONEBOOK **********\n\n\n");
    printf("***************************************\n");
    printf("*                MENU                 *\n");
    printf("*                                     *\n");
    printf("* 1.Add New   2.Print list     3.Exit *\n\n");
    printf("***************************************\n\n");

    ID* ptr=(int*)malloc(21*sizeof(ID));
    do
    {
        printf("Please select (1, 2 or 3): ");
        scanf("%d",&answere);
        if(answere!=1 && answere!=2 && answere!=3)
        {
            printf("...Error... \ngive me a correct answere\n");
        }
        if(answere == 1)
        {
            i++;
            addNew(ptr,i);
        }
        else if(answere==2)
        {
            PrintList(ptr,i);
        }
    }while(answere!=3); 

    return 0;
}

所以正如我所說,我的問題是我無法打印結構的成員,因為我需要使用指針數組打印它們。 我認為我只是沒有寫正確的東西,就像printf中的一個小邏輯錯誤一樣。 我遇到的唯一障礙是需要在main中制作指針數組。

你好像完全迷路了...

一些基礎知識

您正在將指針/引用傳遞給數組的第一項(第一項的地址)以獲取該地址的值(取消引用)您可以做兩件事:

  • *ptr //但我不建議將它與結構一起使用
  • 指針[0]

由於您使用的結構通常很大,因此您應該使用指針,因此存在所謂的“箭頭”運算符,可用於訪問結構指針的成員

  • ptr->名字

所以你的函數看起來像這樣:

    void PrintList(ID *ptr, int l)
    {
         int i;
         printf(" #   First Name       Last Name       Phone Number\n");
         for(i = 0; i < l; i++)
         {
            printf("%2d.   %s       %s       %s\n", 
i, ptr[i].firstName, ptr[i].firstName, ptr[i].phoneNumber);
        }
    }

我還建議使用 '\t' 而不是空格來對齊列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM