C中結構數組'sizeof'的結果?

[英]Result of 'sizeof' on array of structs in C?


In C, I have an array of structs defined like:

在C中,我有一個結構數組,定義如下:

struct D
{
    char *a;
    char *b;
    char *c;
};

static struct D a[] = {
    {
        "1a",
        "1b",
        "1c"
    },
    {
        "2a",
        "2b",
        "2c"
    }
};

I would like to determine the number of elements in the array, but sizeof(a) returns an incorrect result: 48, not 2. Am I doing something wrong, or is sizeof simply unreliable here? If it matters I'm compiling with GCC 4.4.

我想確定數組中元素的數量,但sizeof(a)返回的結果不正確:48,而不是2.我做錯了什么,或者這里的sizeof簡單不可靠?如果重要的話我正在使用GCC 4.4進行編譯。

3 个解决方案

#1


27  

sizeof a / sizeof a[0];

This is a compile-time constant, so you can use it to, for example, create another array:

這是一個編譯時常量,因此您可以使用它來創建另一個數組:

#define N sizeof a / sizeof a[0]
int n_a[N];

#2


37  

sizeof gives you the size in bytes, not the number of elements. As Alok says, to get the number of elements, divide the size in bytes of the array by the size in bytes of one element. The correct C idiom is:

sizeof為您提供以字節為單位的大小,而不是元素的數量。正如Alok所說,為了獲得元素的數量,將數組的字節大小除以一個元素的字節大小。正確的C語言是:

sizeof a / sizeof a[0]

#3


7  

sizeof returns the size in memory of the passed element. By dividing the size of an array by a single element size, you get the elements count.

sizeof返回傳遞元素的內存大小。通過將數組的大小除以單個元素大小,可以獲得元素計數。

Note that the element size may include some padding bytes as well. For this reason, a padded struct (e.g. when a char member is followed by a pointer) will have a sizeof value greater than it members size sum.

注意,元素大小也可以包括一些填充字節。由於這個原因,填充結構(例如,當一個char成員后跟一個指針)將具有大於其成員大小和的sizeof值。

On the other hand, don't let it bother you when counting elements in an array: sizeof(a) / sizeof(a[0]) will still work as smooth as expected.

另一方面,在計算數組中的元素時不要讓它煩惱:sizeof(a)/ sizeof(a [0])仍然可以像預期的那樣平滑。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/12/14/720832cd397bbc501ddd41bd86d722e8.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com