示例
//Visual Studio中加上这句才可以使用scanf() //否则只能使用scanf_s() #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> #define SIZE 10 int sum(int ar[], int n); //等价形式 //int sum(int *ar, int n); //int sum(int *, int); //int sum(int [], int); //int sump(int *ar, int n); //argc: 参数个数 argv[]: 参数数组 int main(int argc, char *argv[]) { int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20}; long answer; answer = sum(marbles, SIZE); printf("The total number of marbles is %ld.\n", answer); printf("The size of marbles is %zd bytes.\n", sizeof marbles); system("pause"); return 0; } int sum(int ar[], int n) { int i; int total = 0; for (i = 0; i < n; i++) total += ar[i]; //如果编译器不支持zd%,可用%u或%lu代替 //这里的ar是一个指向数组的指针,sizeof ar计算的是这个指针所占字节数 printf("The size of ar is %zd bytes.\n", sizeof ar); return total; } //等价形式 /*int sump(int *ar, int n) { int i; int total = 0; for (i = 0; i < n; i++) total += ar[i]; //arr[i]和*(ar+i)相同 return total; }*/
示例:使用指针形参
//Visual Studio中加上这句才可以使用scanf() //否则只能使用scanf_s() #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> #define SIZE 10 int sump(int * start, int * end); //argc: 参数个数 argv[]: 参数数组 int main(int argc, char *argv[]) { int marbles[SIZE] = {20, 10, 5, 39, 4, 16, 19, 26, 31, 20}; long answer; answer = sump(marbles, marbles + SIZE); printf("The total number of marbles is %ld.\n", answer); system("pause"); return 0; } int sump(int * start, int * end) { int total = 0; while (start < end) { //total += *start; //start++; //指针移向下一个数组元素 //与上面两句等效,*与++优先级相同 total += *start++; } return total; }
示例:一元运算符*与++优先级相同
//Visual Studio中加上这句才可以使用scanf() //否则只能使用scanf_s() #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> int data[2] = {100,200}; int moredata[2] = {300,400}; //argc: 参数个数 argv[]: 参数数组 int main(int argc, char *argv[]) { int *p1, *p2, *p3; p1 = p2 = data; p3 = moredata; printf("*p1=%d, *p2=%d, *p3=%d\n", *p1, *p2, *p3); printf("*p1++=%d, *++p2=%d, (*p3)++=%d\n", *p1++, *++p2, (*p3)++); printf("*p1=%d, *p2=%d, *p3=%d\n", *p1, *p2, *p3); system("pause"); return 0; }
指针表示法(尤其与递增运算符一起使用时)更接近机器语言,因此一些编译器在编译时能生成效率更高的代码。