Functions, Arrays, and Pointers
Suppose you want to write a function that operates on an array. For instance, suppose you want a function that returns the sum of the elements of an array. Listing 10.7 shows a program that does this. To point out an interesting fact about array arguments, the program also prints the size of the relevant arrays. (Recall that some pre-ANSI compilers require %ld for printing sizeof quantities.)
Listing 10.7 The sum_arr1.c program.
/* sum_arr1.c -- sums the elements of an array */ #include <stdio.h> #define SIZE 10 long 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 ... |
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.