-2

I am having a problem with pointers. this is an example of what I want

struct Book
{
 char name[10];
 int price;
}

int main()
{

 struct Book b[10];     //Array of structure variables
 struct Book* p;        //Pointer of Structure type
 p = &b;   --- HERE is the ERROR  
}

This is the error part

p = &b;
Yagnik Detroja
  • 921
  • 1
  • 7
  • 22
SHADOW.NET
  • 555
  • 1
  • 5
  • 20

3 Answers3

1

b is an array, which can itself decay into a pointer variable. By writing &b, you actually take the address of that pointer and then you end up with pointer to a pointer. It is enough to just write p = b.

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
  • I did put p=b but i am not able to printf("%i",p[0]->price); or printf("%i",p[0].price); – SHADOW.NET Feb 09 '16 at 08:57
  • What do you mean you are not able to print it? printf("%i",b[0].price) should be working just fine. – Jakub Zaverka Feb 09 '16 at 08:59
  • This is incorrect. `&b` is a pointer to the whole array, whereas `b` decays to a pointer to the first element. In both cases, you get the same address. No pointer to pointer. – undur_gongor Feb 09 '16 at 11:01
0

Try this. I have not checked but this should work. p = b;

now if you want to iterate you array of structure then do this

// Example program
#include <stdio.h>

struct Book
{
     char name[10];
     int price;
};

int main()
{
     struct Book b[10];     //Array of structure variables
     struct Book* p;        //Pointer of Structure type
     p = b;  

     int i = 0;
     for(i = 0 ; i<10; i++)
     {
         printf("Price : %d\n", (p+i)->price);
     }
}
Yousuf Azad
  • 414
  • 1
  • 7
  • 17
-2

b itself is a pointer. Here you can think of arrays as of pointers. So use p=b instead of p=&b

Wapac
  • 4,058
  • 2
  • 20
  • 33
  • I put p=b but i am not able to printf("%i",p[0]->price); or printf("%i",p[0].price); – SHADOW.NET Feb 09 '16 at 08:57
  • 1
    Downvoted, because [arrays are **not** pointers](http://stackoverflow.com/questions/1641957/is-an-array-name-a-pointer-in-c). – user694733 Feb 09 '16 at 09:45
  • 1
    OK, you probably won't agree with that, but I think that in context of this question, OP made mistake because he did not think about arrays as pointers. So based on that, in this context, I believe it is OK to let him think of arrays as pointers. – Wapac Feb 09 '16 at 10:12
  • 1
    It's not appropriate to spread false information in any context. Arrays are already a special case in C type system, and arrays-are-pointers will only cause more confusion down the line. Understanding when arrays *decay* to pointer is vital when using arrays. – user694733 Feb 09 '16 at 10:37
  • Yet sometimes, you make simplifications for beginners, in order to increase the speed of their learning. But fair enough, I change my wording. – Wapac Feb 09 '16 at 10:55