Solved

Pointers/Arrays/Functions

Posted on 2004-10-16
4
278 Views
Last Modified: 2011-04-14
I have a basic understanding of functions, global variables, classes, publics and privates etc....Now I am starting to learn about arrays.
The more I read the more confused I am getting....
Can someone explain how pointers work. I keep reading "pass address of the array" and "pass a pointer to the array".
What does this mean?

Thanks much, Annie
0
Comment
Question by:bananaamy
  • 2
4 Comments
 
LVL 55

Assisted Solution

by:Jaime Olivares
Jaime Olivares earned 100 total points
ID: 12330293
When you "pass" any data to a function, you make a copy to this data to be used by the function, but when you have to pass a big amount of data, like an array, then that is unconvenient. So, usual way is not to pass this data "by value" as explained, but pass it "by reference".

When saying "by reference" I mean to pass just the memory position of the array and not the array itself. That will be enough to let the function to work with data, without taking a complete copy of the data.
A pointer is the same as the address. A pointer IS a memory address of any data.
I can't write an entire chapter about pointers here, but I recommend you to read as many as possible about pointers in C languages books, because it is a key issue.
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 400 total points
ID: 12330603
You define an array like that:

   int array[100];

You now may pass it to a function

    // prototype
    void func( int intarr[] );

    // call the fucntion

    int array[100];
    func(array);

You see in the prototype the the size of the array is not passed to the function, nor the whole array. What is passed is the start address in memory where the compiler made an allocation of 100 integers == 400 bytes. An address passed to a function as an argument you also may call a pointer (as it points to the allocated storage). So, when passed to a function a pointer is equivalent to an array.

   // prototype
   void func(int* pInt);

   // call the function
   int array[100];
   func(array);

Actually, both functions do the same and the function cannot findout whether the pointer passed points to one integer, or 100 integers, or is invalid:

  // call the function using a zero pointer

  int* p = NULL;   // that pointer points to nothing
  func(p);

  // call the function pointing to a single integer
  int i = 10;
  func(&i);   // the & means that not 10 is passed but the address of variable i .  If you lok at that address in memory the value 10 is stored there.


In C++ there is one more way to pass an address (or reference) rather than a value:

   // prototype
   void func(int& refint);

   // call
   int i = 10;
   func(i);

Here the function argument is a reference to the variable i , actually the same as a pointer to i. However, you can't pass an array instead of a pointer as a 'reference to i' always is the address of one single integer and not the start address of a storage that might contain any number of integers,

What is the advantage of passing variables by value, by pointer or by reference?

    int func(int i)
    {
         i = 10;
         return i;
    }

    int i = 20;
    int j = func(i);

the variable i is 20 and j is 10. That means when calling func passing i by value the varaible remains unchanged. The argument gets copied.


    void func(int& i)
    {
         i = 10;
    }
   
    int i = 20;
    func(i);

Here, the function changes the value of i, it is 10 after that. So, passing arguments by reference means the function could change the value (that's why i  didn't have a return value here).


    void func(int* pi)
    {
          *pi = 10;
    }

    int i = 20;
    func(&i);

That does exactly the same as the example before.

   void func(int* pi)
    {
          for (int i = 0; i < 100; ++i)
              pi[i] = i;
    }

   int* p = new int[100];
   func(p);

   cout << p[30] << endl;

That looks different now! The function fills 100 integer values to the stoarage and the values still are available after calling the function. That's the advantage of addresses. You simply pass an address and the function may write to the storage that is at that address in memory.

  void func(int* pi)
    {
          pi = new int[100];
          for (int i = 0; i < 100; ++i)
              pi[i] = i;
    }

   int* p = NULL;
   func(p);

   cout << p[30] << endl;

That doesn't look much different, but the last statement will crash. The difference is that the function allocates memory but the pointer value to the storage will not be passed back to calling function. The pointer p still is NULL and p[30] is invalid. We pass a pointer but the pointer itself is passed by 'value'.

void func(int*& pi)
    {
          pi = new int[100];
          for (int i = 0; i < 100; ++i)
              pi[i] = i;
    }

   int* p = NULL;
   func(p);

   cout << p[30] << endl;

Wow. We 'repaired' the function by passing the pointer by reference. Now, the new pointer value assigned in the function changes the variable 'p' of the calling function and p[30] is well-defined after that.

Regards, Alex
0
 

Author Comment

by:bananaamy
ID: 12330787
maybe what is confusing me is my syntax
this is the statement that I wrote to put data in  my array....

cin>>ainput[n].numCostPerBook;

is this wrong? I was able to make this work,
 however, I cant figure out how to point this data to the void function so that I can run it thru a series of calculations, then point it back to an output array. I am reading , and digesting the above....
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12345184
>> cin>>ainput[n].numCostPerBook;

The statement is correct if you have code like that below:

   struct InputData
   {
         ....
         double numCostPerBook;
   };

   ...
   InputData ainput[10];  // array of InputData

   for (int n = 0; n < sizeof(ainput)/sizeof(InputData); ++n)
   {
          ...
          cin>>ainput[n].numCostPerBook;
   }


     
>> however, I cant figure out how to point this data to the void function

  void makeCalculations(InputData ainput[], int nSize)
  {
        ...
        double totalCost = 0;
        for (int n = 0; n < nSize; ++n)
        {
             totalCost += ainput[n].numCostPerBook;
             ...
        }
 
  }


  int main()
  {
     InputData ainput[10];  // array of InputData

     for (int n = 0; n < sizeof(ainput)/sizeof(InputData); ++n)
     {
          ...
          cin>>ainput[n].numCostPerBook;
     }
     ...
     makeCalculations(ainput, 10);
     ...  
  }

Regards, Alex
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now