Click here to Skip to main content
15,879,095 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've got a problem understanding this syntax:
C++
#include <stdio.h>
 
struct point {
    int value;
};
 
int main()
{ 
    struct point s;
   
    // Initialization of the structure pointer
    struct point* ptr = &s;
 
    return 0;
}


And why when I write: scanf("%d", &ptr->value); then I overwrite the value? I also know that &ptr->value is equivalent to ptr.value. I am a bit puzzled because ptr contains the address of the structure s then why can I put value in ptr when it is the address? Should I be able to put value into *ptr instead I put value in ptr?

What I have tried:

It is a bit conflicting when I compare to normal pointers in which *ptr = &x and to change the value of x, I use *ptr and not ptr.

I belive that I don't say something stupid because I compare it to the basic concept of pointer but maybe it works differently to the normal pointers ;>
Posted
Updated 4-Nov-23 23:55pm
v2
Comments
Richard MacCutchan 1-Nov-23 4:32am    
This is your fifth question on the subject, and it would appear that you still do not understand pointers.
Member 16116753 4-Nov-23 13:43pm    
I've understood the solution below so please stop sticking pins in my questions. If me trying is a problem then why I can't ask ? It's like that if I want to try understand something I see that it is a problem and points out my inability. Thank you ...

1 solution

Yes, when you write
C
scanf("%d", &ptr->value);

if the scanf function call succeed then s.value is changed.

No, &ptr->value is not equivalent to ptr.value.

As matter of fact, ptr->value is equivalent to (*ptr).value, hence you might write
C
&((*ptr).value)
instead of
C
&(ptr->value)
(outer brackets added for clarity).

Try
C
#include <stdio.h>
struct point
{
  int value;
};



int main()
{
  struct point pnt;

  struct point * p = &pnt;

  pnt.value = 0;
  printf("%d\n", pnt.value);

  p->value = 42;
  printf("%d\n", pnt.value);

  (*p).value = -273;
  printf("%d\n", pnt.value);


  scanf("%d", &(p->value));
  printf("%d\n", pnt.value);


  scanf("%d", &((*p).value));
  printf("%d\n", pnt.value);

  return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900