2

Here is my sample code

#include<stdio.h>
void main()
{
 int arr[]={1,2,3,4,5,6};
 char *ptr,a;
 a='c';
 ptr=&a;
 int *ptr1,a1;
 a1=4;
 ptr1=&a1;
 printf("%d  %d   %d",sizeof(arr), sizeof(ptr1), sizeof(ptr));
}

Now, as far as I understand, size of will tell me the size required to store the variable, now the output for this one is

24 4 4

Why is the size of arr=24, after all it's just a pointer and it should be having size =4 ?

Thanks.

4

5 回答 5

5

“……毕竟它只是一个指针……”?不,数组不是指针。Array 是一个数组对象:存储数组元素的固态连续内存块,不涉及任何类型的指针。在您的情况下,数组有 6 个大小为 4 的元素。这就是为什么你的sizeof评估为 24。

关于数组是指针的常见误解已被揭穿数百万次,但不知何故,它时不时地不断出现。阅读常见问题解答,如果您有任何问题,请返回

http://c-faq.com/aryptr/index.html

PS正如@Joachim Pileborg 在他的回答中正确指出的那样,sizeof这不是一个函数。它是一个运算符。


数组行为与指针不同的另一个上下文是一元运算&符(“地址”运算符)。当一元&应用于类型指针时,int *会产生一个类型指针int **。当一元&应用于类型数组时,int [10]会产生一个类型的指针int (*)[10]。这是两种截然不同的类型。

int *p = 0;
int a[10] = { 0 };

int **p1 = &p;      /* OK */
int **p2 = &a;      /* ERROR */
int (*p3)[10] = &a; /* OK */

这是另一个流行的问题(和错误)来源:有时人们希望在应用于数组时&产生一个指针。int **int [10]

于 2012-12-02T18:10:34.967 回答
0

When you have an array, sizeof returns the size of the array (note that it's the size in bytes of the array, not the number of items in the array), otherwise it returns the size of the type or expression.

However, if you pass the array to a function, the array degrades to a pointer and the size information is lost.

Also, technically speaking sizeof is not a function, it's a special keyword in the language, and can be used without parentheses as well when used with expressions.

于 2012-12-02T18:10:19.220 回答
0

数组不会衰减为内部的指针sizeofsizeof(arr)返回为数组分配的总大小,在本例中为6 * sizeof(int).

于 2012-12-02T18:10:39.723 回答
0

来自维基百科

当 sizeof 应用于数组的名称时,结果是整个数组的大小(以字节为单位)。(这是数组名称转换为指向数组第一个元素的指针的规则的少数例外之一。)

于 2012-12-02T18:10:52.453 回答
0

运算符sizeof()不会为您提供数组中元素的数量,而是为您提供事物在内存中占用的字节数。因此:

#include <stdio.h>

int main()
{
  char s[] = { 1, 2, 3, 4, 5, 0 };
  int xs[] = { 1, 2, 3, 4, 5, 0 };

  printf( "sizeof( s ) = %d\n",  sizeof( s  ) );
  printf( "sizeof( xs ) = %d\n", sizeof( xs ) );

  return 0;
}

sizeof( s ) = 6
sizeof( xs ) = 24
于 2012-12-02T18:13:24.893 回答