c/c++中改变子函数里调用的主函数中的数组的值,主函数中的数组本身会变吗?
ringa_lee
ringa_lee 2017-04-17 13:45:18
0
4
1326

函数举例如下:

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_lee
ringa_lee

ringa_lee

reply all(4)
洪涛

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.

迷茫

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...

Peter_Zhu

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

左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!