Sian 发表于 2014-3-3 22:07:33

函数中值传递与地址传递的区别

/* 1、本程序示例旨在说明传递值与传递地址对值的影响; 2、函数passValues()修改的是基本数据类型的值,因此传递进去的是变量的值; 3、函数passValuesAddress()修改的是数组类型的值,传递的是数组的地址; 4、传递值,对原值没有影响,两变量的地址不同; 5、传递地址,修改的原值,因此原值会因此而被修改。 */#include <stdio.h>
void passValues(int n) {
    // 修改的内容仅在本作用域范围内生效;    n = 100;
    // 打印临时变量n的地址;    printf("Address of n is: %p\n", &n);
}
void passValuesAddress(char array[]) {
    // 修改值对原值产生影响    array[0] = 'a';
   // 该地址即传递进来的数组变量的地址;    printf("Address of array is: %p\n", &array[0]);
}

int main() {
    int a = 10;
    // 打印临时变量a的地址;    printf("Address of a is: %p\n", &a);
    printf("a = %d\n", a);
    // 值传递函数;    passValues(a);
    // 在本作用域内,a的值没有被修改过,因而保持不变;    printf("a = %d\n", a);
char chars[5] = {'A', 'B', 'C', 'D', 'E'};
    // 打印数组元素的地址;    printf("Address of chars is: %p\n", &chars[0]);
// 打印数组元素的值;    printf("chars = %c\n", chars[0]);
    // 地址传递函数;    passValuesAddress(chars);
    // 元素的值会受函数的影响;    printf("chars = %c\n", chars[0]);
    return 0;
}
/************************************************************输出结果为:Address of a is: 0x7fff50397c68a = 10Address of n is: 0x7fff50397c2ca = 10Address of chars is: 0x7fff50397c63chars = AAddress of array is: 0x7fff50397c63
chars = a*/
常规整形变量a的值没有因此而改变,但数组元素的值因此而发生了改变;

Sian 发表于 2014-3-3 22:08:18

附上可copy代码:
/*
1、本程序示例旨在说明传递值与传递地址对值的影响;
2、函数passValues()修改的是基本数据类型的值,因此传递进去的是变量的值;
3、函数passValuesAddress()修改的是数组类型的值,传递的是数组的地址;
4、传递值,对原值没有影响,两变量的地址不同;
5、传递地址,修改的原值,因此原值会因此而被修改。
*/
#include <stdio.h>

void passValues(int n) {

    // 修改的内容仅在本作用域范围内生效;
    n = 100;
   
    // 打印临时变量n的地址;
    printf("Address of n is: %p\n", &n);
   
}

void passValuesAddress(char array[]) {

    // 修改值对原值产生影响
    array = 'a';
   
    // 该地址即传递进来的数组变量的地址;
    printf("Address of array is: %p\n", &array);

}


int main() {

    int a = 10;
   
    // 打印临时变量a的地址;
    printf("Address of a is: %p\n", &a);
   
    printf("a = %d\n", a);
   
    // 值传递函数;
    passValues(a);
   
    // 在本作用域内,a的值没有被修改过,因而保持不变;
    printf("a = %d\n", a);
   
    char chars = {'A', 'B', 'C', 'D', 'E'};
   
    // 打印数组元素的地址;
    printf("Address of chars is: %p\n", &chars);
   
    // 打印数组元素的值;
    printf("chars = %c\n", chars);
   
    // 地址传递函数;
    passValuesAddress(chars);
   
    // 元素的值会受函数的影响;
    printf("chars = %c\n", chars);
   
    return 0;
   
}
页: [1]
查看完整版本: 函数中值传递与地址传递的区别