【问题标题】:why the array is sorted from other function in pass by value mode?为什么数组在按值传递模式下从其他函数中排序?
【发布时间】:2021-09-06 10:56:40
【问题描述】:

问题是 x 数组在按值传递模式下从其他函数中正确排序

根据我的理解,数组不能在按值传递模式下从其他函数中排序,它仅在我通过引用传递而我没有传递时才排序,而且 BubbleSort 参数它们只是原始的副本变量,所以当函数完成时,复制变量不会影响主函数中的原始变量,请解释原因并感谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void BubbleSort(int a[])
{
  int temp=0;
  for(int i=0;i<10-1;i++)
    {
      for(int j=0;j<10-1;j++)
        {
          if(a[j]>a[j+1])
          {
            temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
          }
        }
    }
}
int main()
{
  int x[11]={7,6,4,5,8,11,14,37,2,9};
  BubbleSort(x);
  for(int i=0;i<10;i++)
    {
      printf("%d\n",x[i]);
    }
}
  

【问题讨论】:

  • 您不能在 C 中按值传递数组。像 int a[] 这样的参数声明被解析为 int *a。并且调用BubbleSort(x)BubbleSort(&amp;x[0])一样

标签: c pointers pass-by-reference bubble-sort pass-by-value


【解决方案1】:

数组没有赋值运算符。

在这个函数调用中

BubbleSort(x);

具有数组类型的参数表达式被隐式转换为指向其第一个元素的指针。

另一方面,具有数组类型的函数参数被编译器隐式调整为指向数组元素类型的指针。

因此这个函数声明

void BubbleSort(int a[]);

被编译器调整为声明

void BubbleSort(int *a);

所以实际上在 main 中声明的数组 x 的元素是通过指向数组第一个元素的指针通过引用传递的。使用指针算法,函数可以直接访问传递给函数的原始数组的每个元素。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2012-12-18
    • 1970-01-01
    • 2021-02-21
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多