Search

7.4 — Passing arguments by address

There is one more way to pass variables to functions, and that is by address. Passing an argument by address involves passing the address of the argument variable rather than the argument variable itself. Because the argument is an address, the function parameter must be a pointer. The function can then dereference the pointer to access or change the value being pointed to.

Here is an example of a function that takes a parameter passed by address:

The above snippet prints:

value = 5
value = 6

As you can see, the function foo() changed the value of the argument (variable value) through pointer parameter ptr.

Pass by address is typically used with arrays and dynamically allocated variables. For example, the following function will print all the values in an array:

Here is an example program that calls this function:

This program prints the following:

6 5 4 3 2 1

Remember that fixed arrays decay into pointers when passed to a function, so we have to pass the length as a separate parameter.

It is always a good idea to ensure parameters passed by address are not null pointers before dereferencing them. Dereferencing a null pointer will typically cause the program to crash. Here is our printArray() function with a null pointer check:

Passing by const address

Because printArray() doesn’t modify any of its arguments, it’s good form to make the array parameter const:

This allows us to tell at a glance that printArray() won’t modify the array argument passed in, and will ensure we don’t do so by accident.

Addresses are passed by value

When you pass a pointer to a function by address, the pointer’s value (the address it points to) is copied from the argument to the function’s parameter. In other words, it’s passed by value! If you change the function parameter’s value, you are only changing a copy. Consequently, the original pointer argument will not be changed.

Here’s a sample program that illustrates this.

tempPtr receives a copy of the address that ptr is holding. Even though we change tempPtr to point at something else (nullptr), this does not change the value that ptr points to. Consequently, this program prints:

55

Note that even though the address itself is passed by value, you can still dereference that address to change the argument’s value! This is a common point of confusion, so let’s clarify:

  • When passing an argument by address, the function parameter receives a copy of the address from the argument. At this point, the function parameter and the argument both point to the same value.
  • If the function parameter is assigned a different address, that doesn’t impact the argument, since the function parameter is a copy.
  • If the function parameter is dereferenced to change the value being pointed to, that will impact the value the argument is pointing to, since it’s the same value!

The following program illustrates the point:

This prints:

56

Passing addresses by reference

The next logical question is, “What if we want to change the address an argument points to from within the function?”. Turns out, this is surprisingly easy. You can simply pass the address by reference. The syntax for doing a reference to a pointer is a little strange (and easy to get backwards). However, if you do get it backwards, the compiler will give you an error.

The following program illustrates using a reference to a pointer:

When we run the program again with this version of the function, we get:

5 ptr is null

Which shows that calling setToNull() did indeed change the value of ptr from &five to nullptr!

There is only pass by value

Now that you understand the basic differences between passing by reference, address, and value, let’s get reductionist for a moment. 🙂

In the lesson on passing arguments by reference, we briefly mentioned that references are typically implemented by the compiler as pointers. This means that behind the scenes, pass by reference is essentially just a pass by address (with access to the reference doing an implicit dereference).

And just above, we showed that pass by address is actually just passing an address by value!

Therefore, we can conclude that C++ really passes everything by value! The properties of pass by address (and reference) comes solely from the fact that we can dereference the passed address to change the argument, which we can not do with a normal value parameter!

Summary

Advantages of passing by address:

  • It allows a function to change the value of the argument, which is sometimes useful. Otherwise, const can be used to guarantee the function won’t change the argument.
  • Because a copy of the argument is not made, it is fast, even when used with large structs or classes.
  • We can return multiple values from a function.

Disadvantages of passing by address:

  • Because literals and expressions do not have addresses, pointer arguments must be normal variables.
  • All values must be checked to see whether they are null. Trying to dereference a null value will result in a crash. It is easy to forget to do this.
  • Because dereferencing a pointer is slower than accessing a value directly, accessing arguments passed by address is slower than accessing arguments passed by value.

When to use pass by address:

  • When passing pointer values.
  • When passing built-in arrays (if you’re okay with the fact that they’ll decay into a pointer).

When not to use pass by address:

  • When passing structs or classes (use pass by reference).
  • When passing fundamental types (use pass by value).

As you can see, pass by address and pass by reference have almost identical advantages and disadvantages. Because pass by reference is generally safer than pass by address, pass by reference should be preferred in most cases.

Rule: Prefer pass by reference to pass by address whenever applicable.

7.4a -- Returning values by value, reference, and address
Index
7.3 -- Passing arguments by reference

71 comments to 7.4 — Passing arguments by address

  • Jason

    Disadvantages of passing by address:

    Because dereferencing a pointer is slower than accessing a value directly, accessing arguments passed by address is slower than accessing arguments passed by value.

    Could that sentence possibly supposed to read as follows:

    Because dereferencing a pointer is slower than accessing a value directly, accessing arguments passed by address is slower than accessing arguments passed by reference.

    I would think (am assuming) that arguments passed by value would take the longest because they have to be copied.

    [ It turns out that references are usually implemented by the compiler (under the hood) using pointers. Consequently, references aren’t any faster than addresses. They just have a nicer syntax, and are safer to use. -Alex ]

  • Jason

    I think I get it. Passing by value is slow because it does a copy. Passing by reference or address is basically the same thing, just different syntax.

    -----------------------------------
    Comparing these two programs:

    Why doesn’t the second example act as the first example. As the output would be:

    What I’ve noticed is when passing an array by address it changes the address that the pointer points to when inside the function. This causes the original value to never be changed. I guess that’s just how it works.

    Any insight on this issue? Btw, I know that char *array is not an array but a pointer, but once again it really is an array when used with strings right? Just different syntax right?

    • Alex

      > I think I get it. Passing by value is slow because it does a copy. Passing by reference or address is basically the same thing, just different syntax.

      Passing by value can be slow because it makes a copy. If you’re passing a fundamental type (e.g. an int or a double), there’s no problem. But if you’re passing a large struct or class, making a copy can be very expensive. Passing by address (or reference) makes a copy of the address of the argument, instead of copying the entire thing, which can be much faster.

      > What I’ve noticed is when passing an array by address it changes the address that the pointer points to when inside the function. This causes the original value to never be changed. I guess that’s just how it works.

      Good question and insight. As it turns out, pointer parameters are actually passed by value. Consequently, if you try to change what a pointer points to inside a function, it’s the same as changing a variable locally -- as soon as you leave the function, it will revert back to what it was. However, if you dereference the pointer and change the value of what it points to, that won’t be reverted. If you actually want to be able to change the address that a pointer points to inside a function, the best way to do this is to pass the pointer itself by reference:

      void func(char *&address)

      Incidentally, this line of code is dangerous:

      address = “b”

      This is setting the address of the “address” variable to the address of “b”. What is the address of “b”? “b” isn’t a variable, so this doesn’t really make any sense. It probably works in this case due to the way the compiler is dealing with string literals, but I certainly wouldn’t want to trust it.

      > Btw, I know that char *array is not an array but a pointer, but once again it really is an array when used with strings right? Just different syntax right?

      *array in this case is just a pointer. Since it points to an array, you can use it like an array, but it isn’t an array itself.

  • Jason

    Awesome, I get it.

    I’d just like to say, that all made me realize that communicating C++’s logic is an artform.

  • Tom

    1. In your first example function, PrintArray, don’t you have to dereference the pnArray variable, like this??:

    2. Minor typo: “The next logical question is, “What if we want to be able to be able to change the address”

  • weirdolino

    I’m having trouble understanding the conclusions. Under advantages you say
    Because a copy of the argument is not made, it is fast, even when used with large structs or classes.
    and under disadvantages you say
    Because dereferencing a pointer is slower than accessing a value directly, accessing arguments passed by address is slower than accessing arguments passed by value.

    Is passing by reference/address slower or faster than by value? Does it depend on the size of the data passed to the function?

    • When we talk about speed and efficiency with regards to variables, we’re talking about two separate things:

      1) The speed of creating the variable and initializing it’s values. This cost is paid once when the variable is created, and can be significant for large classes that are copied by value. This is why large classes are better passed by pointer or reference than by value, especially if a function is called many times.

      2) The speed of accessing the value stored in the variable. This cost is paid each time the variable is accessed. Although accessing pointers and references is slower than accessing normal variables because of the dereference that takes place, in practice this is rarely a large concern unless you have some kind of loop that accesses the variable hundreds or thousands of times.

  • Kukudum

    In the example you used:
    The function |
    V

    Isn’t PrintArray(anArray, 6); supposed to be PrintArray(&anArray, 6); or am I missing something o.O

    • You are missing the fact that built-in arrays in C++ will decay into a pointer to the array when passed to a function. Since PrintArray() is expecting a pointer for its first parameter, once anArray decays into a pointer, we’re all set.

  • Gareth37

    in ch 6.6 you have this -

    This would be the conceptual equivalent of the following nonsensical example:

    so how comes in the below example we can do

    why isnt it PrintArray(anArray[], 6);
    or PrintArray(anArray[0], 6); the pointer to its first element ?
    i know these dont work because it wont compile
    but it just seems odd we are referring to arrays as
    anArray[] and then it becomes just anArray ?

    • When we declare a pointer, we use the * or [] syntax to let the compiler know that this variable is a pointer as opposed to a normal variable. However, from that point forward, we can just use the variable’s name and the compiler already knows it’s a pointer.

      So if we want to pass the array to a function that expects a pointer, all we need to do is pass the variable itself.

      It’s the same as the following:

      pX already knows it’s a pointer, so when we pass it to printPtr, we don’t need to tell the compiler that it’s a pointer again.

  • jeremy

    hi alex!
    i just want to clarify some points…im quite confused with DEREFERENCING and EVALUATING pointers.
    correct me if im wrong:

    1. my idea is that in below statement, we are assigning the pointer to POINT to the address of nFive
    int *pPtr = &nFive;
    2. on this statement:
    cout << *pPtr;
    we are DEREFERENCING the pointer?
    Kindly clarify.
    Thanks a lot

    • You are correct. We dereference a pointer to get the value of what it’s pointing at.

      int *pPtr = &nFive; // pPtr holds the address of nFive
      cout << pPtr; // prints the address of nFive cout << *pPtr; // prints the value at the address of nFive, which is whatever value was assigned to nFive

  • Bob

    Excuse me but I don’t understand the difference between

    and

    Don’t they both do the same thing? Why bother with the top one (which is more complicated in my opinion) when you can just do the second one?

    • Daniel

      Let me give an example:

      The output of this program is “01134” not “01234” as you might expect. This is because in “PassPointerByValue2” only a local copy of the pointer “thing” is changed whereas in “PassPointerByReference4” the actual pointer “stuff” is changed. Because a pass by reference was used, “thing” was “stuff” not a copy of “stuff” it was “stuff”. I hope that helps you see the difference. (^.^)

      • ming

        This example is very good for study passing pointer in different cases. I spent a hour to get understand it and finally feel comfortable about pointer.
        Here is my explanation of this code:

        Hope this is useful 😀

  • Cuacharpanas

    If string literals don’t have addresses what happen when I write this code which runs without errors from the compiler:

    What str points to?? Moreover, it works the same when a literal string is passed as an argument to a function:

    display(“Important message!”);

    where display definition is:

    someplace str must point to, I think. The prototype void display(char str[]) also works, what is the difference??, may be str is considered as an array, however i tried to change the location it points to and get no error, It worked!

    Hope for replies, Thanks a lot and congratulations for the tutorial, it’s clear and extensive.

    • Alex

      string literals do have addresses, so your examples will work fine. However, string literals may reside in read-only memory, so don’t try and change the contents of a string literal, or your program may terminate with an access violation.

  • Intelus

    I’d like to ask a question. In this post (7.4), you say:

    Note that the length of the array must be passed in as a parameter, because arrays don’t keep track of how long they are. Otherwise the PrintArray() function would not know how many elements to print.

    Examine this short program (explanation below):

    This prints:

    Now, apparently, main() is somehow aware of the fact that anArray is an array with 6 elements while function() sees nothing more than a single address (pointer). Changing the data type yields the same result - pnArray is always 4 bytes (as pointers should be on 32-bit computers) while sizeof(anArray) returns the size of the array’s elements put together (ex. 12 bytes for short, assuming there are 6 elements).

    So I’m wondering, why does main() consider it an array and where is this information stored?

    By the way, regarding the PrintArray function… Wouldn’t it be better to write something like ” if (anArray) PrintArray(…);” inside main() instead of making a null pointer check inside PrintArray? Time is wasted on making a function call which won’t do anything. If it makes the code too complex, you can always use an inline function.

    • bla

      I would like to know the answer to your (first) question too. Because s. th. like:

      would be nice to make the function PrintArray more elegant as it would only require one parameter:

      • Alex

        Yes, main is aware of the fact that anArray is an array of length 6. When anArray is passed to a function, the array decays into a pointer, and the length information is lost.

        I’m honestly not sure why C++ does this, and it’s pretty annoying. But there are ways to work around this (e.g. pass the length separately, or use std::array).

        > By the way, regarding the PrintArray function… Wouldn’t it be better to write something like ” if (anArray) PrintArray(…);” inside main() instead of making a null pointer check inside PrintArray? Time is wasted on making a function call which won’t do anything. If it makes the code too complex, you can always use an inline function.

        Yes, if you know that anArray is null, there’s no point in calling PrintArray() in the first place. However, it’s a function should never assume the caller is doing something reasonable, which is why it’s a good idea to check for null values and handle them gracefully. Otherwise, the program could crash if the caller inadvertently does pass in a null value.

  • Hello there.
    I’m new to C++ (as will soon become obvious!), and I don’t understand why the following function (the second block of code on the tutorial above) prints the CONTENTS of pnArray…

    void PrintArray(int *pnArray, int nLength)
    {
    for (int iii=0; iii < nLength; iii++)
    cout << pnArray[iii] << endl;
    }

    Shouldn't the 'pnArray[iii]' part be dereferenced (ie; '*pnArray[iii]')to get the values IN the pointer array? Or does it not work like that with pointer arrays? Clearly there's something I'm not getting!
    Any help, well appreciated.
    Thanks for all the great tutorials. You have a great way of explaining concepts step by step!

  • kriain1982

    Alex,

    First of all thanks for the tutorials. But I found some thing interesting as below.

    #include

    using namespace std;
    int five = 5;
    int six = 6;

    void check(int *temp)
    {
    printf(“\n*temp : %d\n”, *temp);
    *temp = six;
    printf(“\n*temp : %d\n”, *temp);
    }

    int main()
    {
    int *ptr = &five;
    printf(“\nValue in ptr : %d\n”, *ptr);
    check(ptr);
    printf(“\nValue in ptr : %d\n”, *ptr);
    return 0;
    }

    see the Output :

    Value in ptr : 5

    *temp : 5

    *temp : 6

    Value in ptr : 6

    So, even I am sending pointer (by value), *ptr is getting modified. How can you explain this?

    • Alex

      Yes, this is expected. The address is passed by value, but that address can still be dereferenced to change the value being pointed to. Since both the function parameter and the argument point to this same value, if the function changes the value this way, the argument will be changed as well.

  • zidane3x3

    Thank so much, i used pointer like this (*&pTempPtr) for my program without understanding clearly why but now i get it 🙂 .

  • youssef dirani

    Hello
    “The syntax for doing a reference to a pointer is a little strange (and easy to get backwards”
    What’s the meaning of “easy to get backwards”?

    • Alex

      The correct syntax for a pointer reference is *&pPtr. For a non-pointer variable, you’d create a reference to it like this: &nFoo. Since a pointer is declared as *pPtr, you’d think the correct syntax for a pointer reference should be &*pPtr, with the ampersand on the outside. But it isn’t so.

  • Abarajithan

    Well, I understood something like this as a reason for why the use of ref over variables is slower for smaller datatypes. Tell me if I’m right.

    In a 64 bit machine, an address is 8 bytes, while an int is 4 bytes. So, it takes more time to copy an address than to copy an int. Plus, there’s the time taken for deref-ing as u mentioned. As a result, performance wise, passing by variables is better for smaller size variables while passing by ref is better for bigger structs and classes.

    Another question. If array is really a pointer and if it cannot keep track of its own length, how does sizeof() return the total correct size of arrays?

    • Alex

      No, the difference between copying 4 and 8 bytes should be pretty trivial. The issue comes when you have a struct or class that contains a lot of data, like 1000 bytes or more. That can take a lot of time to copy.

      An array isn’t a pointer, but they’re related. Fixed arrays know their length. However, a fixed array that has decayed into a pointer, or a pointer to a dynamic array doesn’t know the array’s length, because it’s just a pointer.

  • Shivam Tripathi

    Alex…what’s the analysis of this code…plz tell in-depth…O/P is 1   5   1   8….moreover when x & y are coming out of the scope how the pointers are dereferencing them…isn’t they produce DANGLING POINTERS??…plz help

    • Alex

      The pointers will still point to the memory addresses occupied by the (now out of scope) local variables. The contents of those memory locations may still contain the values put there by the local variables -- or they may not.

      So yes, this is a case where the pointers are left dangling (pointing to memory that has been deallocated).

      • Shivam Tripathi

        hmm…got it…it means that although any variable goes out of scope but it’s value may-be still accessible until the OS replaces that stack portion with some other sibling block…correct me if m wrong???

        Moreover…i hv a confusion regarding the pass of the address by reference..consider this snippet:

        Plz..answer both sections…

  • Beware there be dragons! A word of warning that should probably have been in the guidelines is:

    Avoid side effects whenever possible! Yes they are necessary evil from time to time, but avoiding side effects will make your code more predictable and easier to test.

    Most important thing might be in a large project, a lot of function calls will be present, how can you be sure that every change that happens will be the right one? That’s always a hard one, but if most of your functions do not have side effect it’s at least easier (that is usually still not easy at all). Keep your code testable and predictable, it will save you headaches in the long run.

    And whenever you do something with side effects, make sure to document it, even better make it apparent from the function name. Also do consider returning a new object with the result in stead, although that strategy may be troublesome on embedded devices with a limited capacity, it’s easily doable in the era with 16 gigs+ ram in our computers.

  • Kamyar

    Hi Alex
    How can i pass an array to a function by reference?

    • Alex

      To pass an array by reference, you essentially pass it by address and then stick a reference on the front (so you’re passing the address by reference).

      For a dynamic array:

      For a fixed array:

      • Rob G.

        I thought arrays were implicitly passed by reference.  You can modify and change them from within the function body. I’ve written an example showing that with the & or none the result is the same. They also both change the arguments. In the interest of space plz let me know if posting this code would be desirable.

        • Alex

          No, they are not implicitly passed by reference. They are passed by address. Passing them with or without a reference doesn’t matter if all you’re doing is dereferencing them.

          Based on this comment and the previous one, it sounds like you need to revisit the difference between the following two things:
          1) Changing a pointer’s value (e.g. changing the address it points to)
          2) Dereferencing a pointer (e.g. changing the value at the address it points to)

          So when you say, “you can modify and change them from within the function body”, you’re talking about a dereference. You can dereference a pointer or array passed by address and it will impact the original argument. However, if you change a pointer’s value (e.g. point it at a different array), that will not impact the value of the argument UNLESS it’s passed by reference.

  • Sandro

    "It is always a good idea to ensure parameters passed by address are not null pointers before dereferencing them."

    How can one pass a null pointer via argument to a function?

  • Rob G.

    This made sense :

    This didn’t to me:

    Where is the & address operator above example (array,6)?
    Better expressed, to see we are still talking abt addresses:

    May want to consider adding that in. I needed to see an & -

    • Alex

      I added a comment that array decays to a pointer, so no & is needed.

      Although &array[0] works, nobody would write this because it’s redundant.

  • Rob G.

    Hi Alex, wonderful site. Lucky to have this up.

    In the snippet below how am I supposed to know just by the snippet that we are passing by address? I’ve done routines like this, but never associated this with passing by address. I understand that we are passing pointer looking at arg and parameter.

    your code

    • Alex

      The fact that function parameter array is a pointer tells you that we’re passing by address.

      If you only look at the function call itself, there’s no way to tell.

  • Rob G.

    Alex I thought the output below would be 12 99 12, instead its 12 99 99. My understanding this fx would be copying to pointer parameter since passing by address.
    The original pointer argument is changed. Where is my mistake. Thx

    • Alex

      Your mistake is in dereferencing nullptr in the first place. Dereferencing nullptr results in undefined behavior.

      • Rob G.

        Good call, I’ve removed the nullpointer code temporarily to get this code working correctly. The code still seems to replace the function argument. I just can’t get it to copy instead.

        This is my intention with this exercise:
        >> If you change the function parameter’s value, you are only changing a copy. Consequently, the original pointer argument will not be changed.

        BTW I won't take up too much more space on your comments section. I am struggling a bit with 7.4.

        • Alex

          Oh, I see the challenge. The problem here is that you’re not changing the function parameter’s value (which is the address of val_x). You’re dereferencing it, to change the value at the address it’s pointing to. Subtle difference, but important.

          A better test function would be this:

          void ptr_addresses_copy(int * n_ptr)
          {
          int x = 99;
          n_ptr = &x; // make n_ptr point at x instead of whatever it came in as
          std::cout<<"fx copy - see if it copies or replaces"<

  • Shiva

    Hi Alex,

    Nice lesson, detailed and well-explained. You’ve done a good job explaining some confusing topics; however, some wordings felt still a bit confusing, and I also found out some typos:

    Typos:
    #1. As you can see, the function foo() changed the value of the argument value (redundant) through the pointer parameter ptr.
    #2. When you pass an (a) pointer to a function by address, …
    #3. If the function parameter is assigned to (inappropriate) a different address, … (or you should say If a different address is assigned to the function parameter, …)

    These are some confusing wordings:
    #4. tempPtr receives a copy of the address of ptr. (either copy of ptr or copy of the address pointed to by ptr gives more clarity)
    #5. At this point, the function parameter and the argument have the same address, so they both point to the same value. (really topsy-turvy, how can two different pointers have the same _address_? I hope u meant the address stored in them, which is called the _value_ of the pointer. In that case, the function parameter-pointer and the argument-pointer have the same value, which is the address of the common value both of them point to. could be better.)
    #6. The next logical question is, “What if we want to be able to change the address of an argument from within the function?” (ambiguous, more appropriate would be … change the address an argument points to (the argument-pointer’s value) inside the function?" And the answer becomes somewhat obvious to the reader too.)
    #7. Which shows that calling setToNull() did indeed change the address (value) of ptr from &five to nullptr! (again, either it should be value of ptr, or address ptr points to)
    #8. The value (is this a pun? :D) of pass by address (and reference) comes solely from the fact that … (The advantage of pass by address (and reference) is solely the fact that … would be a better phrasing, if no pun was intended)

    Finally, please provide clarification on the following:
    #9. Because literals and expressions do not have addresses, pointer arguments must be normal variables.
          In a comment in the previous post, you said it is possible to "bind a literal to a const reference" So like const references, const pointers too can point to literals, can’t they? So if the pointer parameter is a const, can we pass literals as arguments?
    #10. References are typically implemented by the compiler as pointers.
          So a reference to a pointer would be implemented as a pointer to a pointer, correct?

    Ah, 10 points. Sorry for the hassle, I thought it’d be better to put everything in one comment. 🙂

    • Shiva

      Sorry, I just noticed that #1 was not a typo, I overlooked ‘value’ was a main variable. Let me move it under ‘some confusing wordings’ instead: it’d help if you enclose the second ‘value’ in single quotes. 🙂

    • Alex

      1-8: all updated. Great feedback, thanks!
      9: It’s possible to bind a const reference to a literal, but not a const pointer.
      10: Yes.

      • Shiva

        You’re always welcome. 🙂

        9: But you can bind a const char pointer to a string literal to make a C-style string symbolic constant. So that’s an exception? And in the case of a reference: there are no exceptions: we can bind any literal to the appropriate const reference, correct?

        • Alex

          Yes, I misspoke. It is possible to set a const pointer to an array (of which C-style strings are a subset).

          As far as I know, there are no exceptions with const references.

          • J3ANP3T3R

            Hey Alex can i ask for clarification too. im a bit confused with pass by address.. i have an example here from our older lessons.

            for example this statement is in the main()
                int playerInv[itemType::MAX_ITEMS] = { 0, 0, 0 };

            now this is in the function

            int countTotalItems(int *playerInv)
            {
                int totalItems{ 0 };

                for (int inv=0;inv < static_cast<int>(itemType::MAX_ITEMS);++inv)
                    totalItems += playerInv[inv];

                return totalItems;
            }

            this somehow works but playerInv is a pointer so it is only a variable that holds an address. how did we use it in totalItems += playerInv[inv]; as if it were an array ?

            also another question if i use *playerInv since this is pointing to the value of the address ( which is an array ) can i then use *playerInv[0] *playerInv[1] etc as if it is an array ?

            • Alex

              Remember that operator[] is really just doing pointer arithmetic behind the scenes. So if we have a pointer value, C++ will let us use operator[] with it. If that pointer happens to be pointing to an array, then great, we’re good. If it’s pointing to something else (e.g. a single value) then we’ll end up doing pointer arithmetic into memory that’s used for some other purpose. That would be bad.

              Since operator[] does an implicit dereference, there’s no need to do an explicit dereference before using operator[].

          • J3ANP3T3R

            const char *p1 = "asdf" ;     <- the asdf here has an address ? how to distinguish a value with an address ?

        • Shiva

          Thanks, cleared it! 🙂

  • Jim

    Alex,
    What does if ( ! array) actually do when you talking about passing in a null pointer in the lesson?  I may have missed this in one of your earlier lessons.  To me it reads " if not array ".  But I don’t understand how it would check for a null pointer.  

    THANKS!
    It was a great idea to use one program to demonstrate the three method to make passes to a function.  These three programs alone were very helpful to me. I printed them out side by side, and it’s amazing to see how little needs to be changed to make them all work.

    • Alex

      Array is a pointer, so it can be holding a memory address or a null value. This is checking whether array is holding a null value.

  • Nyap

    The people who would find the fact that the address is technically passed by value difficult to understand have been already wiped out during chapter 6 xD

    Btw, is there a good resource dedicated to how memory works and things like that? I’m getting a 3ds hack soon that lets you make Action Replay (https://en.wikipedia.org/wiki/Action_Replay) style cheats and some people at the forum that I use reccomended that I do some more dedicated research on memory

    • Alex

      I’m not aware of a good, easy to understand resource on memory. Memory management is complicated, especially on modern operating systems.

  • KIRPAL SINGH A/L HARWAN SINGH

    what do you mean by >> "no & needed"

    • Alex

      With a normal variable, you need to use an ampersand to get the address of the variable (convert it to a pointer).

      e.g.

      Since arrays implicitly convert to a pointer to the first element of the array, you don’t need to use an ampersand.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter