+ 1
Doubts about pointers and function
int add_up (int *a, int num_elements); int main() { int orders[5] = {100, 220, 37, 16, 98}; printf("Total orders is %d\n", add_up(orders, 5)); return 0; } int add_up (int *a, int num_elements) { int total = 0; int k; for (k = 0; k < num_elements; k++) { total += a[k]; } return (total); } -Why should i declare the function before main? The script works anyway -You can't really use an array as an argument of a function? I've tried and it works anyway (like in the code down below) int add_up (int a[ ], int num_elements) { int total = 0; int k; for (k = 0; k < num_elements; k++) { total += a[k]; } return (total); }
1 Answer
+ 2
0) The function must be declared before main or more precisely, before it is being called. You can even put the declaration (the prototype) inside main for that matter. The only thing is that it must precede the call, as the program flow goes from up to down, and the compiler must know that some function exists before you use it.
1) An array is nothing but a pointer. The compiler allocates the memory, and then assigns the address of the first element to the array. You can do this process yourself by using malloc, but the only difference will be that the memory you allocate will be allocated at runtime. All you need to retrieve the entire array is the address of the first element of the array, stored in a pointer named as the array's name, and the size, as a C-array does not know its size by itself.
That is why you can use either of these to pass an array:
int * arr, int arr[], int arr[<size>]
The third one is a bit different as it only allows passing of arrays having an equal allocation size.