Anyone help with the code in tutorial 48 please !! Pointers confusion

+1 Xuekun Lu · January 21, 2016


I am confused with the lines 19 20. Since "pointsArray" is a pointer, and it stores address, why in "scanf(" %d", &pointsArray);" , why not using “scanf("%d",pointsarray)”  From line 20, it indicates  pointsArray[2]= an integer instead of a address ?

Thanks a lot for the help !

Post a Reply


Oldest  Newest  Rating
0 Linguist Llama · January 23, 2016

I am confused with the lines19 20. Since "pointsArray" is a pointer, and it stores address, why in "scanf(" %d", &pointsArray[i]);"

Your confusions are numerous. The one you're asking about here is precedence. Think about the precedence of operators like multiplication, addition, division and subtraction... Now think about what the precedence of pointer[subscript] and &address-of might be; they might be the reverse of what you're thinking.

The pointer[subscript] operation follows the pointer link so the expression pointsArray[i]. pointsArray[i] is an int. Hence the ampersand to form a pointer to that int object. &pointsArray[i] can also be written pointsArray + i; this way there are no pointer[subscript] or &address-of operators to confuse you.

why not using ?scanf("%d",,pointsarray[i])?

scanf needs a pointer to an int to be able to modify the int that is pointed to. I have an exercise for you:

#include <stdio.h>
int change(int fubar) {
   fubar = 42;

int main(void) {
   int x = 0;
   printf("x before change(): %d\n", x);
   printf("0 after change():  %d\n", 0);
   printf("x after change():  %d\n", x);

Your first task is to explain how it could be that the first call to change() would modify the integer constant 0...

Once you've done that, note that the first call to change() can't possibly change the constant 0. Run the code and see for yourself...

Next, work out how to make the change function modify x in a way that main can see. You'll know you've succeeded when the value of x after the call prints 42 instead of 0.

If you need a hint, start by looking up pass-by-value in Google (THIS IS IMPORTANT!)... then try using pointers.
0 Xuekun Lu · January 22, 2016
Hi Krootushas,

Thanks so much for your reply, it clears my question now !
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator