-1

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);
  }
 }
IcanCode
  • 509
  • 3
  • 16

1 Answers1

2

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
    }
 }
CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • warning: passing argument 1 of 'input' from incompatible pointer type however code works well – IcanCode Dec 20 '20 at 16:31
  • you don't need to change the line `input(b)` actually. that should get rid of the warning. – CS Pei Dec 20 '20 at 16:34
  • 2
    @IcanCode - the code as shown here is correct and when used with remainder of your code as shown, should compile with no warnings. (My answer was misleading, and now deleted.) – ryyker Dec 20 '20 at 16:43