0

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];
}
4
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by ontherocks
0

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.

0

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 by ontherocks: n/a

0

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
}
1

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 by Fbody: n/a

Votes + Comments
+1 for correctness. My favorite poster?
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.