CLKing31------------------Calculation of array size

Calculation of array size

giantmfc123 2019-03-28 22:51:51 1794 Collection 1
Category column: Growth and progress
Copyright
When we create a data, we want to calculate the size of the array:
    int arr[5] = {1,2,3,4,5} ;
    int arrsize = sizeof(arr)/sizeof (arr[0]);
    int arrsize2 = sizeof(arr)/sizeof (int);
    qDebug() << "before: arrsize = "<< arrsize;
    qDebug() << "before: arrsize2 = "<< arrsize2;
1
2
3
4
5 After
executing the result, the size is 5

2. After the modified array is passed to the function as a parameter, the size cannot be calculated in this way.

void ArraySize::print(int *p)
{     qDebug() << "";     int arrsize = sizeof(p)/sizeof (p[0]);     int arrsize2 = sizeof(p)/sizeof (int);     qDebug() << "after:  arrsize = " << arrsize;     qDebug() << "after:  arrsize2 = " << arrsize2;     qDebug() << "*p_size =" << sizeof(p);     qDebug() << "*p[0]_size =" << sizeof(p[0]);     for (int i = 0; i < 5; i++)     {         qDebug() << "*p[" << i << "] = " << p[i];executing the result, the size is 2, the result is wrong14 After13121110987654321}     }


























Because after the transfer, the size of sizeof§ is actually the size of the pointer. In a 32-bit system, the size is 4, and in a 64-bit system, the size is 8. p[0] is an int, and the size is 4. So the result is 2. And the real should be 5. So this way is wrong.
3. If the parameter is an array, the result is the same as the pointer, and both are wrong. Because pointers and arrays are essentially the same.

void ArraySize::print2(int p[5])
{
    qDebug() << "";
    qDebug() << "*p_size =" << sizeof(p);
    qDebug() << "*p[0]_size =" << sizeof(p[0]);
    for (int i = 0; i < 5; i++)
    {
        qDebug() << "*p[" << i << "] = " << p[i];
    }
}
1
2
3
4
5
6
7
8
9
10
执行结果后,大小是2,结果是错的

4. If you want to use the array size as a function parameter, you must pass the size as a parameter.

void ArraySize::print3(int *p, int size)
{
    qDebug() << "";
    qDebug() << "size =" << size;
    qDebug() << "*p_size =" << sizeof(p);
    qDebug() << "*p[0]_size =" << sizeof(p[0]);
    for (int i = 0; i < 5; i++)
    {
        qDebug() << "*p[" << i << "] = " << p[i];
    }
}
1
2
3
4
5
6
7
8
9
10
11
执行结果;

————————————————
Copyright Statement: This article is the original article of the CSDN blogger "giantmfc123", and it follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement for reprinting. .
Original link: https://blog.csdn.net/mafucun1988/article/details/88880534

Guess you like

Origin blog.csdn.net/qq_43662480/article/details/114680164