10

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?

Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199

7 Answers7

5

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;
}
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • today i learn one more thing..people dont understand things by simple syntex but they understand by small programs ..!! – Jeegar Patel Oct 03 '11 at 11:46
  • 3
    @Mr.32: Unfortunately, we learn best from concrete examples, trial and error and our own mistakes, not as much from theories, abstract things or someone else's experience. – Alexey Frunze Oct 03 '11 at 11:50
  • Let me tell you one thing @Mr32 your answers is nothing more than just copy paste on someone else answers – Amit Singh Tomar Oct 03 '11 at 13:25
2

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

Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
2

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

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
1

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]);
    }
aQwus jargon
  • 133
  • 3
  • 18
1

You can put the array into a structure like this:

struct int_array {
    int data[128];
};

This structure can be passed by value:

void meanval(struct int_array ar);

Of course you need to now the array size at compile time and it is not very wise to pass large structures by value. But that way it is at least possible.

quinmars
  • 11,175
  • 8
  • 32
  • 41
0
void func(int a)
{
   int* arr = (int*)a;
   cout<<arr[2]<<"...Voila" ;
}

int main()
{
   int arr[] = {17,27,37,47,57};
   int b = (int)arr;
   func(b);
}
VJS
  • 1
-1

There is one more way: by passing size of array along with name of array.

int third(int[], int ); 

main() {
   int size, i;
   scanf("%d", &size);
   int a[size];
   printf("\nArray elemts");
   for(i = 0; i < size; i++)
       scanf("%d",&a[i]);
   third(a,size);
}
int third(int array[], int size) {
    /* Array elements can be accessed inside without using pointers */
} 
clearlight
  • 12,255
  • 11
  • 57
  • 75
abinjacob
  • 31
  • 6