Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between scanf("%d", *p) and scanf("%d", p)?

Pointers are a new thing for me and I'm struggling to understand it, but I won't give in and hopefully learn it.

What would be the difference between scanf ("%d", *p) and scanf ("%d", p)?

In examples I saw that if I want to input some value in a variable, I should use scanf ("%d", p). That doesn't make sense to me. Shouldn't it be scanf ("%d", *p)?

I interpret it as: "put some integer value where the pointer is pointing" and for instance it is pointing on variable x and then it should be x = 10, but it isn't. And how then to use scanf() and pointers to set values in an array?

Where and what am I getting wrong? I'm trying to learn this using C language, since it is the one which I'm supposed to use in my class.

For example:

#include <stdio.h>
int main () {
    float x[10], *p;
    int i;
    p = &x[0];
    for (i = 0; i < 10; i++) {
        scanf("%d", p + i);
    }
    for (i = 0; i < 10; i++) {
        printf("%d", *(p + i));
    }
    return 0;
}

Why is only p + i in the first for () {} and *(p + i) in the second loop? I would put *(p + i) also in the first for () {}. *(p + i) to me is like: "to what the (p+i)th element is and make it equal some value".

like image 536
Nick Avatar asked Apr 15 '14 22:04

Nick


1 Answers

*p means go to the place p points to
&p means take the address of p, or "get a pointer to" p

int i;
scanf("%d", &i); // gives scanf a pointer to i

int i;
int *p = &i;
scanf("%d", p); // a more contrived way to say the same thing

The obligatory visual explanation is Pointer Fun with Binky.

You can read the types from right to left:

int *p => "p has type int *" => p is a pointer to an int
int *p => "*p has type int" => *p is the int pointed to by p

like image 67
Ryan Haining Avatar answered Sep 24 '22 07:09

Ryan Haining