I don't understand value given with sizeof() with Arrays

时间:2018-03-22 00:52:49

标签: c++ arrays sizeof

In this code snippet the output I get is 24. Why is that?

int data[] = { 5, 6, 7, 1, 4, 0 };

int n = sizeof(data);

cout << n << endl;

2 个答案:

答案 0 :(得分:8)

sizeof返回24,因为你有6个整数,每个整数占4个字节。

答案 1 :(得分:1)

首先,您必须记住arrayspointers不同。

如果是数组,sizeof()将返回整个数组的大小,在您的示例中为24个字节,因为您有6个int元素,每个都是4个字节。

现在看一下这段代码:

int *data = { 5, 6, 7, 1, 4, 0 };
int n = sizeof(data);

在这种情况下,sizeof()将返回指针的大小,而不是数组。指针在32位应用程序中是4个字节,在64位应用程序中是8个字节。

相关问题