#include #define MONTHS 12 int main(void) { int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int index; for (index = 0; index < MONTHS; index ) printf("Month - has %d days.n", index 1, * (days index)); return 0; } 可以看到* (days index)其实和days[index]是一个效果的。 在函数中,我们可以这么传入数组int sum(int * ar),但是这样只能得到首元素的地址,却不知道数组个数(自然我们能把数组个数当成第二个参数传入),还可用int ar[]代替,这是指向数组的指针,是一个指针(因为重要所以说两遍),为什么强调这一点,看这个程序就知道了: 代码如下 | 复制代码 | #include #define SIZE 10 int sum(int ar[], int n); int main(void) { 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 %lu bytes.n", sizeof marbles); return 0; } int sum(int ar[], int n) { int i; int total = 0; for (i = 0; i < n; i ) total = ar[i]; printf("Te size of ar is %lu bytes.n", sizeof ar); return total; } 来看看输出: Te size of ar is 4 bytes. The total number of marbles is 190. The size of marbles is 40 bytes. 调用函数的时候输出的是4,这是因为函数内,它并非是一个数组,只是一个int类型的指针,int类型为4个字节,而在main中,数组本身由10个int类型的数组成,所以是40。 请随时记得:* (days index)其实和days[index]是一个效果的 除了指定数组大小外,还有什么办法指定: 代码如下 | 复制代码 | #include #define SIZE 10 int sump(int * start, int * end); int main(void) { 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); return 0; } int sump(int * start, int * end) { int total = 0; while (start < end) { total = *start; start ; } return total; } 答案是一样的,因为索引从0开始,所以marbles SIZE指向数组结尾后下一个元素(再往后结果是未知的)。 |
|
|