What is the meaning of the following?

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

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

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

So, can I do this:

 int (*p)[5] = &sampleArray? 
+4
source share
5 answers

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

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

Since sampleArray is the array itself, and the unary & operand is one of the places where it supports this identity, this means that &sampleArray is a pointer to the entire array.

+9
source

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

However, they do not have the same type:

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

int (*p)[5] declares a pointer p array of five int s. Ergo

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

Code example:

 #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 is the same for both methods.

 $ ./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. It is a free software; see source for copy conditions. There is no guarantee; not even for COMMERCIAL VALUE or SUITABILITY FOR A PARTICULAR PURPOSE.

0
source

which is called insilization of the array. array is a set of similar data types, such as int, char, floating point number.

0
source

Source: https://habr.com/ru/post/1306080/


All Articles