Solved

Pointers/Arrays/Functions

Posted on 2004-10-16
4
277 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

744 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

16 Experts available now in Live!

Get 1:1 Help Now