#include<stdio.h> int main() { void method1(int& val); void method2(int* addr); void swap(int* val1, int* val2); printf("Test 1 ...\n"); //默认情况下,num是一个变量(值) int val = 7; printf("原始的值为:%d\n", val); method1(val); printf("method1后的值:%d\n", val); method2(&val); printf("method2后的值:%d\n", val); printf("\nTest 2 ...\n"); //"int*"标志了addr是一个指针(地址) int* addr; //*addr = 12; //Error:段错误,因为是先将12赋给指针变量(地址)addr,再取其值 addr = &val; printf("原始的值为:%d\n", *addr); method1(*addr); printf("method1后的值:%d\n", *addr); method2(addr); printf("method2后的值:%d\n", *addr); printf("\nTest 3 ...\n"); int a = 2; int b = 3; int* ap = &a; int* bp = &b; printf("a = %d, b = %d\n", *ap, *bp); swap(ap, bp); printf("a = %d, b = %d\n", *ap, *bp); } //"int&"标识val是一个变量(值) void method1(int& val) { val = val + 1; } //"int*"标志了addr是一个指针(地址) void method2(int* addr) { *addr = *addr + 1; } //val1和val2都是指针变量,即是地址。 //不管是普通变量还是指针变量,实参变量与形参变量之间的数据传递都是单向的“值传递” //所以,我们不能通过函数来改变val1和val2的“值”(地址),但可以改变它里面的内容 void swap(int* val1, int* val2) { int temp; temp = *val1; *val1 = *val2; *val2 = temp; }
#include<stdio.h> int main() { void printArray(int arr[], int num); void printMultiArray(int (*arrs)[4], int lows, int cols); //或者void printMultiArray(int [][4], int lows, int cols); void inverse(int arr[], int num); int arr[] = {0,1,2,3,4,5,6,7,8,9}; printArray(arr, 10); int arrs[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; printMultiArray(arrs, 3, 4); inverse(arr, 10); int i; for(i = 0 ; i < 10 ; i ++ ) { printf("%d\n", arr[i]); } } //一唯数组 void printArray(int arr[], int num) { int* p; //数组名"arr"表示数据第一个元素的地址 for(p = arr; p<(arr+num); p ++) { printf("%d\n", *p); } } //多维数组 void printMultiArray(int (*arrs)[4], int lows, int cols) { int i, j; for(i = 0 ; i < lows ; i ++ ) { for(j = 0 ; j < cols ; j ++) { //以下三式等价 printf("%d ", *(*(arrs+i) + j)); //或printf("%d ", arrs[i][j]); //或printf("%d ", *(arrs[i] + j)); } printf("\n"); } } //反转数组元素 void inverse(int* arr, int num) { int *p, *d; int mid = num/2; for(p = arr, d = arr+num-1 ; p<(arr+mid); p++, d--) { int temp; temp = *p; *p = *d; *d = temp; } }