Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i pass an array function without using pointers

Tags:

c

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?

like image 405
Amit Singh Tomar Avatar asked Oct 03 '11 11:10

Amit Singh Tomar


People also ask

How can you pass an array to a function?

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.

What are two ways to pass array to a function?

There are two possible ways to do so, one by using call by value and other by using call by reference.

How do you pass an array reference in C++?

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.

Why is not possible to pass an array to a function?

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. "


4 Answers

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]);
    }
like image 95
aQwus jargon Avatar answered Oct 11 '22 00:10

aQwus jargon


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;
}
like image 5
Alexey Frunze Avatar answered Oct 19 '22 02:10

Alexey Frunze


How about varargs? See man stdarg. This is how printf() accepts multiple arguments.

like image 2
Michał Šrajer Avatar answered Oct 19 '22 02:10

Michał Šrajer


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

like image 2
Jeegar Patel Avatar answered Oct 19 '22 04:10

Jeegar Patel