Solved

Pointers/Arrays/Functions

Posted on 2004-10-16
4
283 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
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 viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

623 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