-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09.c
64 lines (39 loc) · 1.85 KB
/
09.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdlib.h>
#include <stdio.h>
int SumOfElements(int A[], int number_of_elements){
printf("The number of elements this array has is %d.\n", number_of_elements);
int i, sum = 0;
for (i = 0; i < number_of_elements; i++){
sum = sum + A[i];
}
return sum;
}
int SumOfElementsWithSize(int A[]){ // The interpreter considers int A[] = int *A
int number_of_elements = sizeof(A) / sizeof(A[0]);
printf("\nThe WithSize function sees the size of A = %ld bytes (pointer to integer), and the size of A[0] = %ld bytes.\n", sizeof(A), sizeof(A[0]));
int i, sum = 0;
for (i = 0; i < number_of_elements; i++){
sum = sum + A[i];
}
return sum;
}
int main(int argc, char *argv[]){
// Passing arrays as function arguments
// Creating an array of integers
int A[] = {1, 2, 3, 4, 5};
// Calling the function that returns the sum of the elements of the array
// We have got to know a way to get the number of elements of the array
// sizeof() returns the size of some data structure in bytes
int number_of_elements = sizeof(A) / sizeof(A[0]);
int total = SumOfElements(A, number_of_elements);
printf("The sum of the elements in this array is %d.\n", total);
// Calling the sum function without passing the number of elements in the array
total = SumOfElementsWithSize(A);
printf("The sum of the elements (with size calculated inside the function) is %d. (totally WRONG)\n", total);
// This new result is wrong, because when the compiler sees an array passed as a parameter,
// it doesn't create a copy of the array inside the function.
// Actually, in the function SumOfElementsWithSize one pointer to the first element of the
// array (that exists inside main()) is created.
// We always call by reference when we pass arrays as arguments
return 0;
}