c - int 类型的数组不会从函数调用中修改

标签 c pointers parameter-passing sizeof

<分区>

由于某些我不知道的原因,main() 中的数组在应该修改的时候没有得到修改。 "a" 不是通过引用传递的吗?有人可以指导我一下吗?

代码如下:

#include "stdio.h"

void sort(int list[])
{
    //int list[] = { 4, 3, 2, 1, 10 };
    int n = sizeof(list) / sizeof(int);
    int min = 0;
    int temp = 0;
    for (int i = 0; i < n; i++)
    {
        min = i;
        //profiler.countOperation("compSort", n, 1);
        for (int j = i + 1; j < n; j++)
        {
            if (list[j] < list[min])
            {
                min = j;
                //profiler.countOperation("compSort", n, 1);
                    }
        }
        if (min != i)
        {
            //profiler.countOperation("compSort", n, 1);
            temp = list[min];
            list[min] = list[i];
            list[i] = temp;
        }
    }
}

int main()
{
    int a[5] = {4, 3, 2, 1, 10};
    sort(a);
    printf("%d\n", a[0]);
    for (int i = 0; i < 5; i++)
    {
        printf("%d", a[i]);
    }
    return 0;
    /*int arr[MAX_SIZE];
    for(int t = 0; t < 1; t++)
    {
        for (int n = 100; n < 3000; n = n + 300)
        {
            FillRandomArray(arr, n);
            sort();
            printf("done %d \n", n);

            if (!IsSorted(arr, n)
            {
                printf("error sort \n");
            }
        }
    }
    profiler.addSeries("TotalSort", "cmpSel", "atribSel");
    profiler.createGroup("SortMediu", "TotalSort", "cmpSel", "atribSel");
    profiler.showReport();*/
}

最佳答案

问题出在

 int n = sizeof(list) / sizeof(int);

数组,一旦作为函数参数传递,就会衰减到指向第一个元素的指针。它们不再具有数组属性。所以,这里的list被调整为指向int的指针。

引用 C11,章节 §6.7.6.3

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

解决方案:您需要在调用方计算大小(在数组衰减发生之前)并将其作为不同的参数传递给被调用函数。

关于c - int 类型的数组不会从函数调用中修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43136044/

相关文章:

c++ - C/C++ : Force Bit Field Order and Alignment

c - 如何初始化指针指向的结构的成员?

c - 从动态分配的指针数组打印错误

linux - 如何将密码传递给bash脚本

c - 什么注册const char * const * name;是什么意思,为什么这个变量在函数之外?

c - HAL_RCC_OscConfig 耗时太长(约 170 μS),我需要它在从 STOP 唤醒时小于 50 μS

c - 将指针重置为字符数组

c++ - 这些大小对于变量数组和变量指针数组是否正确?

c - C 函数中的参数传递

parameter-passing - vala 是 "pass by reference"还是 "pass by value"?