C:数组传值调用和传地址调用

传地址调用

对数组进行修改:排序...

c 复制代码
#include <stdio.h>

// 函数用于交换两个整数的值
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// 函数用于对整数数组进行升序排序
void sortArray(int *arr, int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]); // 通过传地址调用swap函数交换数组元素
            }
        }
    }
}

int main() {
    int arr[] = {5, 2, 9, 3, 6};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("原始数组:");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    sortArray(arr, size);

    printf("\n升序排序后的数组:");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

传值调用

只使用数据,不对数据修改

函数接收参数的拷贝(数组的副本)

c 复制代码
#include <stdio.h>

// 函数用于对整数数组进行升序排序
void sortArray(int arr[], int n) {
    // 使用冒泡排序算法对数组进行排序
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // 交换两个元素的位置
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {5, 2, 9, 3, 6};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("原始数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    // 调用函数对数组进行排序
    sortArray(arr, n
相关推荐
练习时长一年2 小时前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
小白菜又菜7 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n8 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo8 小时前
leetcode 2483
数据结构·算法·leetcode
sevenez9 小时前
Vibe Coding 实战笔记:从“修好了C坏了AB”到企业级数据库架构重构
c语言·笔记·数据库架构
Xの哲學9 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢9 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
油泼辣子多加9 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
一路往蓝-Anbo9 小时前
【第20期】延时的艺术:HAL_Delay vs vTaskDelay
c语言·数据结构·stm32·单片机·嵌入式硬件
Aaron158810 小时前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程