search

Home  >  Q&A  >  body text

c/c++中改变子函数里调用的主函数中的数组的值,主函数中的数组本身会变吗?

函数举例如下:

void test(float L[25][30])
{
    for (int i = 0; i < 25; i++)
        for (int j = 0; j < 30; j++)
            L[i][j] = L[i][j] + 1;//简单测试
}
int main()
{
    float L[25][30];
    L[i][j]=......
    ...
    test(L);
    return 0;
}

我的测试是:主函数中的L确实会改变。请问,这是因为数组本身是指针。还是因为我在哪里搞错了,需要另写指针返回?谢谢。

ringa_leeringa_lee2805 days ago1391

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:47:18

    void test(float L[25] [30])
    The above statement is equivalent to
    void test(float L[][30]);
    or
    void test(float (*L)[30]);
    When an array is used as a function parameter, it will be treated as a pointer. So the characteristics of the array are gone. You can try sizeof(L) inside the test(L) function and sizeof(L) outside the function. It can be seen that the two outputs are different. The array has array length information, and the pointer But there is no length information pointing to the content, which is why many times, when designing APIs, APIs involving array and pointer parameters generally pass a length information parameter.
    In addition, test(L);
    where L refers to the address of L[0][0], you can try to output **L.
    Summary:
    1. Arrays are not pointers. Arrays have array length information, but pointers do not.
    2. When used as a function parameter, the array will be regarded as a pointer.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:47:18

    They are all arrays and will definitely change
    Because you declared that a large piece of memory is allocated and the array name you pass is the first address of the memory
    Then when you operate the array, you still modify the data in this memory area
    So...

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:47:18

    Yes, when used as a function parameter, the array name will become a pointer, so you are actually operating the memory area pointed to by the pointer, which is the memory of the array you applied for in the main function stack

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:47:18

    When an array is used as a function parameter, it will degenerate into a pointer of the same type.
    The test function operates on the memory area corresponding to the original array.

    reply
    0
  • Cancelreply