vj01
vj01

Reputation: 663

What is the meaning of the following?

int sampleArray[] = {1,2,3,4,5};

I understand that the sampleArray now points to the first element of the array.

However, what does it mean when I say &sampleArray? Does it mean I am getting the address of the sampleArray variable? Or does it mean a two-dimensional array variable?

So, can I do this:

int (*p)[5] = &sampleArray?

Upvotes: 4

Views: 376

Answers (5)

satyam
satyam

Reputation: 123

that is called insilization of an array. array is collection of similar type of data like int,char,float number like that.

Upvotes: 0

Tanj
Tanj

Reputation: 1354

Some sample code:

#include <stdio.h>

int main()
{
  int a[] = {1,2,3,4,5};
  int (*p)[5] = &a; 
  //Note
  //int (*p)[5] = a; // builds (with warnings) and in this case appears to give the same result

  printf( "a = 0x%x\n" , (int *)a);
  printf( "&a = 0x%x\n", (int *)(&a));
  printf( "p = 0x%x", (int *)p);

  return;
}

The output - same for both ways.

$ ./a.exe 
a = 0x22cd10
&a = 0x22cd10
p = 0x22cd10

Compiler

$ gcc --version gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) Copyright (C) 2004 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 0

caf
caf

Reputation: 239341

No, sampleArray does not really point to the first element of the array. sampleArray is the array.

The confusion arises because in most places where you use sampleArray, it will be replaced with a pointer to the first element of the array. "Most places" means "anywhere that it isn't the operand of the sizeof or unary-& operators".

Since sampleArray is the array itself, and being the operand of unary-& is one of the places where it maintains that personality, this means that &sampleArray is a pointer to the whole array.

Upvotes: 9

James McNellis
James McNellis

Reputation: 355327

The name of an array evaluates to its address (which is the address of its first element), so sampleArray and &sampleArray have the same value.

They do not, however, have the same type:

  • sampleArray has a type of int* (that is, a pointer-to-int)
  • &sampleArray has a type of int (*)[5] (that is, a pointer to an array of five ints).

int (*p)[5] declares a pointer p to an array of five ints. Ergo,

int (*p)[5] = &sampleArray; // well-formed :)
int (*p)[5] = sampleArray;  // not well-formed :(

Upvotes: 7

Related Questions