Reputation: 13811
I'm a beginner in C and I'm trying to understand the concept of pointer arithmetic:
I have a code like this :
#include<stdio.h>
void main(){
int a[10];
if(a)
printf("%d\n",*a);
}
Which prints the address of first element in array a
. That's fine. But in my printf
statement I'm using the *
operator to print the value.
But when I look at my if
statement, I wonder how without *
operator, if
is working on a
?
I mean without *
operator, how the if
statement accesses the object the pointer points to?
I guess i'm clear enough about my doubt, thanks in advance.
Upvotes: 1
Views: 111
Reputation: 182619
Which prints the address of first element in array a
In your code *a
is equivalent with a[0]
. You're not printing any address, just some uninitialized value.
no my question is without * operator, how the if statement accesses the object the pointer points to
In your code if (a)
doesn't access the contents, it only tests the address of a - which will never evaluate to 0.
Upvotes: 3
Reputation: 33368
if (a)
basically checks if a is a null pointer.
When you declare int a[10] you allocate a space of memory of 10 integers, starting at the address 'a'.
When you printf *a the compiler prints the first element becuase you're telling it to print the element at the address *(a + offset) which in your case offset = 0;
To convince yourself you can try doing
int *a=null;
if (a)
{
//code here won't be executed because a points to a null reference
}
Upvotes: 0
Reputation: 4031
In C there is no type for a boolean so the body of an if-statement is executed when the condition doesn't equal 0 (zero). And it's quite sure that a
doesn't point to the address 0
, so the condition evaluates to true
.
Upvotes: 0