简体   繁体   中英

Accessing the member of structure passed to a function as array of structure

I have a structure named book which is defined as:

struct book
{
char name[30];
};

I created an array of the structure in this manner:

  struct book b[2];

I passed it to a function and want to acess it like b[i].name since i am passing array i have to deal with pointer in my function.since i am using a for loop i wrote ptr[i]->name but that is not working.

I found a similar question at Passing an array of structs in C however that doesnot solve my problem. My total program is:

#include<stdio.h>

 struct book
 {
   char name[30];
 };
void input(struct book [2]);
void display(struct book [2]);

 int main()
 {
 struct book b[2];
 struct book;
 input(b);
 display(b);
 }

void input(struct book *b1)
{
for (int i = 0 ; i < 2 ; i++)
{
 printf("Enter the name of book\n");
 scanf(" %[^\n]s",b1[i]->name);
}

}
void display(struct book *b1)
{
 for (int i = 0 ; i < 2 ; i++)
  {
 printf("Name of book: %s",b1[i]->name);
  }
 }

The member can be accessed like the following, (the same fix for both display() and input() )

void display(struct book *b1)
{
    for (int i = 0 ; i < 2 ; i++)
    {
        printf("Name of book: %s",b1[i].name); // here
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM