Why do we use & before ptr->points?

  • Context:
  • Thread starter Thread starter evinda
  • Start date Start date
  • Tags Tags
    Pointers
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
evinda
Gold Member
MHB
Messages
3,741
Reaction score
0
Hello! (Wave)

I have a question... 🧐

https://dyclassroom.com/c/c-passing-structure-pointer-to-function

At the Complete code stated at the site above, at this part:

Code:
for (i = 0; i < 3; i++) {
    printf("Enter detail of student #%d\n", (i + 1));
    printf("Enter ID: ");
    scanf("%s", ptr->id);
    printf("Enter first name: ");
    scanf("%s", ptr->firstname);
    printf("Enter last name: ");
    scanf("%s", ptr->lastname);
    printf("Enter Points: ");
    scanf("%f", &ptr->points);
    
    // update pointer to point at next element
    // of the array std
    ptr++;
  }
why when the input is an array we do not use & and when the input is not array we use it?

So why we use only & before ptr->points?

Which is the difference? :oops::unsure:
 
Physics news on Phys.org
First this can vary with the compute language. Are you referring to C++?

Do you understand what a "pointer" is?

A computer has many "memory locations" in which it can store numbers. A pointer (to x) is, technically, a memory location which contains the memory location in which "x" is stored. Putting & before a pointer changes it to the memory location in which "x" is stored. More specifically, if I have the number "7" stored somewhere in memory, the pointer "P" is the memory location in which "7" is stored while "&P" is the number "7" itself.
 
evinda said:
why when the input is an array we do not use & and when the input is not array we use it?

Which is the difference?

First off, we need to provide a memory address to scanf.
Generally, we do that by putting & in front of the variable that we want to fill. (Nerd)

If the data member is an array, there is actually no difference whether we put an & in front of it or not.
Suppose we have char arr[10];.
Then the C standard says that arr is treated as the same memory address as &arr[0].
If we use &arr, we are saying we want to have the memory address of the array, which is the same thing.
And we can't take the address of a memory address - that does not make sense. (Nerd)

evinda said:
So why we use only & before ptr->points?

ptr->points is not an array. Instead it is a floating point number.
So we have to put & in front of it to get its memory address. (Nerd)