I have been asked in an interview how do you pass an array to a function without using any pointers but it seems to be impossible or there is way to do this?
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
There are two possible ways to do so, one by using call by value and other by using call by reference.
Arrays can be passed by reference OR by degrading to a pointer. For example, using char arr[1]; foo(char arr[]). , arr degrades to a pointer; while using char arr[1]; foo(char (&arr)[1]) , arr is passed as a reference.
Because the starting address of the array is passed, the called function knows precisely where the array is stored. Therefore, when the called function modifies array elements in its function body, it's modifying the actual elements of the array in their original memory locations. "
simply pass the location of base element and then accept it as 'int a[]'. Here's an example:-
main()
{
int a[]={0,1,2,3,4,5,6,7,8,9};
display(a);
}
display(int a[])
{
int i;
for(i=0;i<10;i++) printf("%d ",a[i]);
}
Put the array into a structure:
#include <stdio.h>
typedef struct
{
int Array[10];
} ArrayStruct;
void printArray(ArrayStruct a)
{
int i;
for (i = 0; i < 10; i++)
printf("%d\n", a.Array[i]);
}
int main(void)
{
ArrayStruct a;
int i;
for (i = 0; i < 10; i++)
a.Array[i] = i * i;
printArray(a);
return 0;
}
How about varargs? See man stdarg
. This is how printf() accepts multiple arguments.
If i say directly then it is not possible...!
but you can do this is by some other indirect way
1> pack all array in one structure & pass structure by pass by value
2> pass each element of array by variable argument in function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With