Difference between C/C++ array and pointer

The name of the array is the pointer. This sentence is believed to be very familiar to many people. In order to facilitate the understanding of the relationship between arrays and pointers when getting started with C language, such simplification is usually done.
But in fact, there are still some differences between arrays and pointers.
Look at such a piece of code:

#include <stdio.h>

int GetSize(int data[]) {
    
    
    return sizeof(data);
}

int main() {
    
    
    int data1[] = {
    
    1, 2, 3, 4, 5};
    int size1 = sizeof(data1);

    int* data2 = data1;
    int size2 = sizeof(data2);

    int size3 = GetSize(data1);

    printf("%d %d %d", size1, size2, size3);
    return 0;
}

This code is modified from "Jianzhi Offer (2nd Edition) Famous Enterprise Interviewers Lecture Typical Programming Questions" by He Haitao

The output is:

/* 64 位机器 */
20 8 8
/* 32 位机器 */
20 4 4
/* 64位机器上指针类型占 8 个字节, 32 位机器上指针类型占 4 个字节 */

The results show that
data1 represents an array and also represents the first address of the array, and sizeof(data1) represents the size of the array (each integer occupies 4 bytes, and 5 integers occupy 20 bytes in total).
data2 shows that even if a pointer points to the first address of the array, it cannot fully represent the array, and its essence is still a pointer.
data3 indicates that when an array is passed into a function as a parameter, the array will automatically degenerate into a pointer.

Reference: "Jianzhi Offer (2nd Edition) Famous Enterprise Interviewers Lecture Typical Programming Questions" by He Haitao

Guess you like

Origin blog.csdn.net/m0_59838087/article/details/120643731