0

Is it necessary to use function as a pointer while returning array from other function to main function in c?

#include <stdio.h> int * get_evens(); int main() { int *a; int k; a = get_evens(); /* get first 5 even numbers */ for (k = 0; k < 5; k++) printf("%d\n", a[k]); return 0; } int * get_evens () { static int nums[5]; int k; int even = 0; for (k = 0; k < 5; k++) { nums[k] = even += 2; } return (nums); }

22nd Jan 2019, 7:25 AM
Ankit Sharma
3 odpowiedzi
+ 7
In C, the name of the array is essentially a pointer which always points to the first element of an array. To return an array from a function, the function return type should be a pointer of the same type as the array you want to return. This is necessary since the C syntax does not allow you to return an entire array, but rather pointers.
22nd Jan 2019, 7:49 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Your function isn't a pointer, it is returning a pointer. As Hatsy Rei said, an array is basically a pointer, and a pointer contains a memory address. As a matter of fact, this synthax is valid: #include <stdio.h> int main(void) { int a[3] = {1, 2, 3}; int* ptr = a; //a contains an address printf("%d %d", a[1], ptr[2]); //can use ptr[x] return 0; } No matter what, "return nums;" returns a memory address, and the pointer a stores what it receives as a memory address, because of their respective types. It just so happens here that sizeof(int) is equal to sizeof(int*) (ie the size of a pointer/memory address), so there is no disturbance if you turn "int* get_evens()" into "int get_evens()". If you were to use a return type shorter than that, the memory address would get truncated and you wouldn't get what you would expect when printing your array in the main (ie you would get either garbage values or a memory access violation).
22nd Jan 2019, 3:08 PM
Zen
Zen - avatar
0
But even if I don't use function as pointer why does this program works.
22nd Jan 2019, 8:43 AM
Ankit Sharma