Home  >  Q&A  >  body text

c++ - 数组的大小的问题

#include <iostream>

using namespace std;

int main()
{
    char*a[]={"zzzz","zz","zzzzzzz"};
    cout << sizeof(a) << endl;
    return 0;
}

为什么输出是24呢?为什么数组的大小不是5 + 3 + 8 = 16呢?

天蓬老师天蓬老师2764 days ago514

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 14:50:36

    a stores the addresses of three string constants. It does not store three strings directly. An address is also a pointer

            |----------| 
            |  xxxxxx  |       
            |----------|        |--------|
     a -->  | pointer1 | -----> | "zzzz" |
            |----------|        |--------|      |------|
            | pointer2 | ---------------------> | "zz" |
            |----------|        |-----------|   |------|
            | pointer3 | -----> | "zzzzzzz" |
            |----------|        |-----------|
            |   xxxxx  | 
    sizeof(a) == 3 * sizeof(pointer) = 24

    If you have a 32-bit operating system, the pointer length is 4 bytes, and 64-bit is 8 bytes. It can be deduced that your compilation environment is 64-bit

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:50:36

    C/C++ declarations cannot be read from left to right. Instead, you have to find the identifier first. Move the cursor to the right. When there is nothing on the right, the cursor moves to the left. When there is nothing on the left, go to the previous level. The first step is repeated for brackets, and ends when there are no more brackets. [1]

    That is, char* a[] means,

    a is an array of pointers to char's

    When using a string literal to initialize char*, the pointer variable stores the address of the string constant in memory.

    That is to say,

    sizeof(a) == 3 * sizeof(char*)

    On 64-bit systems,

    sizeof(char*) == 8

    So

    sizeof(a) == 24

    In addition, the size of an array in C/C++ is always equal to the size of a single element in the array multiplied by the number of elements in the array

    This means that whenever the size of an array is calculated, several unequal numbers will not be added together.

    If you want the memory space occupied by a variable to be equal to the sum of its parts, you can write like this:

    #include <stdio.h>
    
    int main() {
      struct a {
        char a[5];
        char b[3];
        char c[8];
      } a = {"zzzz", "zz", "zzzzzzz"};
    
      printf("%lu\n", sizeof(a)); // 16 = 5 + 3 + 8
    }
    

    reply
    0
  • Cancelreply