开发者

use of sizeof operator

开发者 https://www.devze.com 2023-02-20 11:18 出处:网络
The output offollowing program #include<stdio.h> int main(){ int *p[10]; printf(\"%ld %ld\\n\",sizeof(*p),sizeof(p));

The output of following program

#include<stdio.h>
int main(){
    int *p[10];
    printf("%ld %ld\n",sizeof(*p),sizeof(p));
}

is

8   <--- sizeof(*p) gives  size of single element in the array of int *p[10] 
80  <--- sizeof(p) giv开发者_如何学Goes  size of whole array which is 10 * 8 in size.

now see the following program

 #include<stdio.h>
 #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
 int array[] = {23,34,12,17,204,99,16};

  int main()
  {
      int d;
      printf("sizeof(array) = %ld \n",sizeof(array));
      printf("sizeof(array[0]) = %ld \n",sizeof(array[0]));
      printf("sizeof int %ld\n",sizeof(int));
      printf("TOTAL_ELEMENTS=%ld \n",TOTAL_ELEMENTS);
      for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
          printf("%d\n",array[d+1]);

      return 0;
  }

is

sizeof(array) = 28 
sizeof(array[0]) = 4  <--here
sizeof int 4
TOTAL_ELEMENTS=7 

What I am not able to understand is why is the sizeof(array[0]) different in both the outputs.


int *p[10]; is an array of pointers.

*p is the first element of that array of pointers. So it is a pointer to an integer. It is not an integer.

int array[] = {23,34,12,17,204,99,16}; is an array of integers. So array[0] is the first element of that array. So it is an integer.

The size of a pointer to an integer (*p) and an integer (array[0]) are different.

So sizeof(*p) and sizeof(array[0]) are different.

sizeof(p) gives the size of the array of pointers. So it is: 10 x 8 = 80.
i.e. (number of elements) x (size of one element)

sizeof(array) gives the size of the array of integers. So it is: 7 x 4 = 28.


In the first example, the element is a pointer to int, while in the second example it's just int. You can see that the pointer has 8 bytes, the int just 4 bytes.


In the first case, you've created an array of pointers to int, so their size is 8, not 4.


In the first example the size of a pointer is used and in the second the size of an integer. They may have different sizes especially on 64 bit systems.


array[0] has type int

*p has type int*

This perhaps demonstrates the stylistic folly of writing

int *p[10] ;

rather than

int* p[10] ;

where the second makes it clearer that int* is the type of the array being declared.


The 64-bit environment sets int to 32 bits and long and pointer to 64 bits ..

*p is a pointer - 8 bytes
sizeof(p) -is size of 10 pointers - so 80 bytes

Chances are you have AMD64 machine - check this for details (including other options) http://gcc.gnu.org/onlinedocs/gcc/i386-and-x86_002d64-Options.html

0

精彩评论

暂无评论...
验证码 换一张
取 消