I have a code wherein I pass a whole array to a function.
Is it possible to do exactly the same thing using pointers?

#include <iostream>
using namespace std;

void func(int array[]);

int main()
{
      int array[] = {10,20,30,40};
      func(array);
      cin.get();
      return 0;
}

void func(int array[])
{
     cout << array[1];
}

You're not passing the whole array. The compiler (usually) passes by reference when dealing with arrays... whether or not you specify it that way.

You're not passing the whole array. The compiler (usually) passes by reference when dealing with arrays... whether or not you specify it that way.

Ok, in that case how could the code be re-written using regular pointer and reference syntax (*, &).

Edited 6 Years Ago by ontherocks: n/a

I would suggest you to read the chapter on pointers from your text-book before asking such questions here. These topics are covered in any standard books...
Here is the syntax...

#include <iostream>
using namespace std;

void func(int array[]);

int main()
{
      int array[] = {10,20,30,40};
      func(array);
      //    func(&(array[0]));  //  AN ALTERNATIVE MENTHOD OF SENDING
      cin.get();
      return 0;      //  IT'S GOOD TO SEE BEGINNERS USE int main() INSTEAD
}                    //  OF void main(). GJ!

void func(int *array)
{
     cout << array[1];
     //     cout << *(array + 1);   //  AN ALTERNATIVE MENTHOD OF PRINTING
}

Actually, this is better:

#include <iostream>
using namespace std;

void func(int *const array);

int main()
{
      int array[] = {10,20,30,40};
      func(array);
      //    func(&(array[0]));  //  AN ALTERNATIVE MENTHOD OF SENDING
      cin.get();
      return 0;      //  IT'S GOOD TO SEE BEGINNERS USE int main() INSTEAD
}                    //  OF void main(). GJ!

void func(int *const array)
{
     cout << array[1];
     //     cout << *(array + 1);   //  AN ALTERNATIVE MENTHOD OF PRINTING
}

That way you don't run the risk of losing your pointer to the first element of your array. You can still modify the contents of the array though.

Edited 6 Years Ago by Fbody: n/a

Comments
+1 for correctness. My favorite poster?

Thank you.
This example made things more clear than the material in textbooks I have read.

This article has been dead for over six months. Start a new discussion instead.