phschoen
phschoen

Reputation: 2081

referenced array == array

could you tell my why the value of a referenced array and the value of the array itself has the same value?

i know a is a type of int* but with &a it should be int** or am i wrong?? so the value should be a pointer to the a int pointer. example code:

    #include <stdio.h>

    int main()
    {
        int a[10];
        printf("a without ref.: 0x%x\n",a);
        printf("a with    ref.: 0x%x\n",&a);
        return 0;
    }

http://ideone.com/KClQJ

Upvotes: 3

Views: 184

Answers (4)

John Bode
John Bode

Reputation: 123458

Given an array declaration T a[N], the expression &a has type "pointer to N-element array of T (T (*)[N]) and its value is the base address of the array. In that respect, the unary & operator behaves the same for arrays as it does for any other data type.

What's hinky is how C treats the array expression a. Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an array expression of type "N-element array of T" (T [N]) will be replaced with ("decay to") a pointer expression of type "pointer to T" (T *) and its value will be the address of the first element of the array. IOW, a == &a[0].

Since the address of the first element of the array is the same as the base address of the entire array, the expressions a and &a yield the same value, but the types are different (T * as opposed to T (*)[N]).

Upvotes: 1

coco
coco

Reputation: 49

Name of the array will implicit convert to a pointer ,except for two situation ,the one situations is "&array",the other is "sizeof(array)".In both cases,name of the array is a array ,not a pointer .

For example:

int a[10];
int *p;
p = a;        //a is a pointer
p = &a;       //a is a array,&a is a constant pointer
sizeof(a);    //a is array

Upvotes: 1

plan9assembler
plan9assembler

Reputation: 2984

if there is int *p which point a, then,

a+0 == &a[0] == p+0 == &p[0] : address

*(a+0) == *(&a[0]) == *(p+0) == *(&p[0]) : data

a == &a == &a[0]

Upvotes: 0

Alok Save
Alok Save

Reputation: 206526

Name of the array decays to an pointer to its first element in this case.

Upvotes: 3

Related Questions