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

Array of type int doesn't get modified from the function call

出于某种我不知道的原因,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.

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

以这种方式传递给函数的数组会衰减为指针,因此

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

结果 sizeof(int *)/sizeof(int)

您可以使用 VLA 解决问题

#include "stdio.h"

void sort(size_t n, int list[n])
{
    size_t min = 0;
    int temp = 0;

    for (size_t i = 0; i < n; i++)
    {
        min = i;
        //profiler.countOperation("compSort", n, 1);
        for (size_t 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(void)
{
    int a[5] = { 4, 3, 2, 1, 10 };
    sort(sizeof(a) / sizeof(a[0]), a);
    printf("%d\n", a[0]);
    for (int i = 0; i < 5; i++)
    {
        printf("%d", a[i]);
    }
    printf("\n");

    return 0;
}