Home  >  Q&A  >  body text

c++ - 遍历数组时遇到的一基础问题?

int a[] = {1, 2, 3, 4, 5};
for (int i = 0; i < sizeof(a) / sizeof(int); i++)
{

}

这里的a不是代表指针吗?为什么sizeof(a)得到的大小和指针的大小不一样?是因为这个是const指针吗?还是涉及到指针和数组名的本质区别?谢谢大家。

PHP中文网PHP中文网2715 days ago689

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 15:25:56

    Arrays and pointers are two types.
    Array names can be implicitly converted to pointers to the first element. The type of
    a is int[5], and sizeof(a) is equivalent to sizeof(int[5]) rather than sizeof(int *).

    reply
    0
  • 黄舟

    黄舟2017-04-17 15:25:56

    There is still a difference between array pointers and ordinary pointers. After all, when the array is defined, its element type and number can be determined

    Only when the compiler cannot infer whether it is an array or an ordinary pointer, it will be calculated based on the size of an ordinary pointer sizeof
    For example, in a function declaration, void f(int* a), because any pointer may be passed as the parameter a Enter, it is impossible for the compiler to infer whether it is an array
    so sizeof(a) = sizeof(int*)

    But in the case of your question, the compiler can clearly infer that a is a 5-element integer array, so sizeof(a) = sizeof(int[5])

    reply
    0
  • 迷茫

    迷茫2017-04-17 15:25:56

    To put it simply, the essential difference:
    The variable name is the name of the memory area and has no name at runtime. a and p are only meaningful in source code and compilation time.
    The memory named a is a piece of memory of type int[5] with 5 ints.
    p is named a memory space with only one int pointer of type int.
    a[2] is directly translated into the third unit of that memory space during compilation.
    p[2] is translated into p, take out the value of the int* memory space, and add 2 to get the memory address of the memory space.
    int const p only limits the memory space pointed by p to only have one int pointer to be immutable.

    reply
    0
  • Cancelreply