I have a class function - which I am trying to pass array values - however the function returns the values even when I don't use the reference &. WHY? COULD SOMEONE EXPLAIN THIS?

Block example;    // create an instance of the class 'Block'

        int Array1[3] = {0,0,0};     // start value
        int Array2[3] = {1,0,0};
        int Array3[3] = {1,5,0};
         
        // Program should add the three values together
        //    (0,0,0) + (1,0,0) + (1,5,0) = (2,5,0)
        // and reference the value to Array3

        cout << Array3[0];    // = 1
        example.addLink(Array3);
        cout << Array3[0];   // = 2 ???

Here is the addLink function

int addLink(int addSpace[3]){ /* [B]I don't need &addSpace[3][/B] */

        // allocate memory for a (temporary) new node
        node *newLink = new node;
        if(newLink == NULL){ return 0; /*error*/}

        // Set new Link to null
        newLink -> nextLink = NULL;

        // sets the first node
        if(firstLink == NULL){

            firstLink = newLink;

            for(int i = 0; i < 3; i++){
                firstLink -> space[i] = addSpace[i];
            }
        }
        // sets a pointer to the previous node
        else{

            for(int i = 0; i < 3; i++){

            	// Calculate and store the linked list coordinates
                newLink -> space[i] = prevLink -> space[i] + addSpace[i];

                // Return the newLink data to the caller
                addSpace[i] = newLink -> space[i];
            }

            prevLink -> nextLink = newLink;
        }


        // Set the last and previous link to the new link
        lastLink = prevLink = newLink;

        return 1;   // return true: the link has been added
    }

Recommended Answers

All 2 Replies

Anytime you are passing in (type a[]) to a method the call is converted into (type *a) where the array is passed in by pointer. I don't believe there is much of a workaround. If you need your original array intact, copy it memberwise into another array and keep that in main().

In fact, c++ array uses computed address, when you pass it to a function, it actually passes the starting pointer of it (the one with index [0]).

So when you modify the content, it is modifying the actual memory that you uses it.

I will copy the whole array if I do so.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.