Reputation: 79
I'm new to pointers...
While assigning values to an array using pointer we use:
int *arr;
arr = malloc(10*sizeof(int));
for(i=0;i<10;i++)
{
scanf("%d",(arr + i));
}
But while assigning to a variable we use
int *arr = malloc(sizeof(int));
*arr = 10;
So why cant we use,
scanf("%d",*(arr + i));
Why is it showing error?
Upvotes: 1
Views: 65
Reputation: 1937
In
scanf("%d",(arr + i));
(arr + i)
already is a pointer to the i-th element of the array arr
. Had you scanf
ed into a "single" variable, you would have had to pass its address (=pointer to that variable).
scanf("%d", &some_int_variable);
Why is it showing error?
Dereferencing:
scanf("%d",*(arr + i));
would be wrong, because it wouldn't pass the pointer to the i-th array member to read to, since scanf()
requires a pointer to the argument specified by the format tag, not a value.
Upvotes: 2
Reputation: 36102
scanf
takes an address (pointer) of a value, the format specifier tells what kind of pointer.
scanf("%d", (arr + i) )
means you are giving scanf
the address arr
plus an offset of i
,
when you write *arr = 10;
you can also write it as *(arr + 0) = 10;
so you are de-referencing the value and assigning it 10 in other words you cannot give this to scanf
since it wants a pointer.
so
arr = malloc(10*sizeof(int));
+---+---+---+---+---+---+---+---+---+---+
arr ->|0 | | | | | | | | | 9 |
+---+---+---+---+---+---+---+---+---+---+
arr + i is an address in the range 0..9, de-referencing a value in the array you write *(a+i)
but
arr = malloc(sizeof(int));
+---+
arr ->| |
+---+
writing *ar
r you are de-referencing the one value you allocated
*arr = 10;
+---+
arr ->| 10|
+---+
however writing
scanf("%d", arr);
is fine since arr is a pointer that points to an integer and scanf takes a pointer.
Upvotes: 0
Reputation: 44329
Because scanf
requires a pointer. Not a value. *(arr+i)
is the value so if you passed that to scanf
the function could not change the value so that it was effective after the function call.
It requires a pointer so that it can change the value of the object pointed to and make the change effective after the call.
It is like all function calls in c
. They pass by value. Inside the function the value may be changed but as soon as the function returns any such changes are lost.
However, if the value passed is the value of a pointer, the function may change the value of the object pointed to by the pointer. Such a change will still be effective when the function returns.
A simple example:
void f(int a)
{
a = 10; // This change is lost when the function returns
}
void g(int* a)
{
*a = 10; // This change will survive when the function returns
}
int main(void)
{
int a = 0;
f(a);
printf("%d\n", a); // will print 0
g(&a);
printf("%d\n", a); // will print 10
return 0;
}
Upvotes: 0