0

Why do we use ' *' in function declaration when we are returning array from a function even if the array points to first element

If array is pointing to first element then the pointer will automatically get the address. So, why' *' is used in return datatype in function declaration https://code.sololearn.com/cXyZhxG7F3JE/?ref=app

18th Aug 2020, 12:20 PM
Ankush Kurmi
2 Respostas
+ 2
Array name evaluates to a pointer that points to the first element of array. return type `int *` indicates that function will return a pointer that points to integer (This integer will be first element of array) Arrays are contiguous memory locations. So if you know where the first element in array is stored you can find any other element in array by pointer arithmetics. if you add `n` (integer value) to a integer pointer `a` it'll point to location a + sizeof(int). In this way adding 1 gives you address of 2nd element, adding 2 gives address of 3rd element and so on. You didn't ask but note why is array made static : If you don't make it static it'll have life time as long as program control is in enclosing function (get_multiples) and when function returns array can get removed from memory at any time. Accessing such a (dangling) pointer may corrupt memory or crash program.
18th Aug 2020, 12:42 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
0
Thanks a lot :)
18th Aug 2020, 1:11 PM
Ankush Kurmi