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];
}

Recommended Answers

All 5 Replies

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 (*, &).

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.

commented: +1 for correctness. My favorite poster? +1

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.