类型、表达式和数组维度

Types, expressions and arrays dimensions

我将 similar question 的答案标记为红色,其中对此事进行了广泛而直接的讨论。我想确定我给他们的解释是否正确。

例如,我的 textbook 在练习 6.24 中指出 "The sizeof operator can be used to find the number of bytes needed to store a type or an expression. When applied to arrays, it does not yield the size of the array."

#include<stdio.h>

void f(int *a);

int main(){
    char s[] = "deep in the heart of texas";
    char *p  = "deep in the heart of texas";
    int a[3];
    double d[5];

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

    f(a);
    return 0;
}

void f(int *a){
    printf("In f(): sizeof(a) = %d\n", sizeof(a));
}

即便如此,对我来说也不是那么明显。因此,我想与您简要讨论一下输出:

sizeof(s) = 27
sizeof(p) = 8
sizeof(a) = 12
sizeof(d) = 40
In f(): sizeof(a) = 8

然后:

sizeof(s) = 27

这里27就是s组成的字节数,每个char组成一个字节。这与 sizeof 的定义形成对比,因为它 return 似乎是 _size_of 数组。在这一点上,我认为 char s[] = "deep in the heart of texas" 被视为 表达式 是否正确?

sizeof(p) = 8

在这里,我们有一个指针char *。由于sizeof"finds the number of bytes needed to store a type",我假设一个指针char *存储在8个字节的内存中。我说得对吗?

sizeof(a) = 12 and In f(): sizeof(a) = 8

这个案例让我特别没有把握。我发现的唯一相关区别是,在 f() 中,数组 a 作为 parameter 传递:指向其基数的指针。和以前一样,一个指针存储在 8 个字节的内存中。我对么?如果是这样,则必须将 12 视为存储表达式 int a[3]?

所需的内存量
sizeof(d) = 40

又是return数组的维度d,即5段,每段8字节。但是,同样,我们不是在谈论数组,而是在考虑表达式 double d[5]。正确吗?

感谢您与我分享您的知识和经验!

很多文字,我没有全部阅读,但这是我的答案:

char s[] = "deep in the heart of texas";   // sizeof = length of string + 1
char *p  = "deep in the heart of texas";   // sizeof is size of pointer = 8
int a[3];                                  // size of 3 ints
double d[5];                               // size of 5 doubles

并且在f中,你正确地声明它是一个指针,所以它的大小就是指针的大小。

就这些了...

简要说明:

1) sizeof(s) = 27:包含NUL-终止符的字符串长度。请注意,sizeof(char) 是标准的 1。

2) sizeof(p) = 8:您系统上 char* 的大小。

3) sizeof(a) = 12:在main中,是的,这是数组中元素的数量乘以每个元素的大小。由此我们可以推断出 sizeof(int) 是 4.

4) sizeof(d) = 40: sizeof(double)乘以元素个数

在函数f中,传递的数组已经退化为指针类型。 sizeof(a) 很可能是 8。标准并不 坚持 sizeof(char*)sizeof(int*) 相同,但我从未遇到过桌面不是这种情况的 PC。