Thread: Passing an array to function

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    3

    Passing an array to function

    Could someone please help. I've been trying to work fix this piece of code to put into a project but I could not get it to work. I keep getting this error C2664: 'SumOfNumbers' : cannot convert parameter 1 from 'int' to 'double []' . I've worked every thing piece by piece but when I try to pass the array to the function I get the error and don't know what it means. Does C++ not allow what I'm trying to do?

    Code:
    #include <iostream>
    using namespace std;
    
    void SumOfNumbers(double Nbr[], int size); 
    
    int main()
    {
        int size, Sum;
        int *arrayNumbers;
        //const int size = 10;
        cout << "How much values to be added: ";
        cin >> size;
    
        arrayNumbers = new(nothrow) int[size];
        if(arrayNumbers == 0)
            cout << "error";
        else
        {
            for(int i = 0; i < size; i++)
            {
                cout << "Enter number: ";
                cin >> arrayNumbers[i];
                
            }    
            SumOfNumbers(arrayNumbers, size);
            //delete[] arrayNumbers; 
        }
    
        //const int *number = 0;
        //number = new int[size];
        //double arrayNumbers[10]; 
    
        //for(int i = 0; i < size; i++)
        //{
        //    cin  >> arrayNumbers[i];
        //}
        ////cout << *arrayNumbers; 
        //int value = SumOfNumbers(*arrayNumbers, size);
        ////cout << "Value is: " << Sum;
    
        system("pause");
        return 0;      
    }
    
    void  SumOfNumbers(int Nbr[], int size)
    {
        int Sum = 0;
        for(int i = 0; i < size; i++)
        {
            Sum += Nbr[i];
        }
        cout  << "Your numbers are: ";
        for(int i = 0; i < size; i++)
            cout << Nbr[i] << ", sum is " << Sum << "\n";
        //return Sum;
    }
    Last edited by Linkx16; 06-08-2013 at 05:53 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    1) Your line 4 and line 44 don't match. An array of double is not an array of int. Similarly, a pointer to double is not a pointer to int. In other words, you need to make up your mind whether sumOfNumbers adds up doubles or ints. They are not interchangeable. My following observations assumed you have fixed that, and decided to make SumOfNumbers() works with ints, not doubles (since that's how main() uses it).

    2) When calling SumOfNumbers(), it either needs to be supplied an array or a pointer. arrayNumbers is a pointer. *arrayNumbers is not. Remove the asterix.

    The following observations aren't the question you asked about .... view them as unsolicited advice from someone who is concerned you are developing or being taught very bad habits.

    3) Whoever told you to use operator new to allocate an array should be summarily shot. If you decided to do that on your own, wash your mouth out with soap. Look up the vector type in the library. It has facilities so you can resize it, and it keeps track of its size. So, you could just write SumOfVectors() to accept a single argument which is a reference to std::vector<int>. The beauty is, doing that supplies both the data and information about the size. The vector is a package deal.

    4) The standard library has an algorithm called accumulate() which computes the sum of elements in any container (an array like you are sort-of trying to use is one type of container, a std::vector<int> is another). You can use that to implement you SumOfNumbers(). Or, since using an algorithm is a one-liner, have main() use the it directly - and eliminate all need for the SumOfNumbers() function.

    5) Don't use system("pause"). If you want the program to wait for user input, use something like "int input = cin.get()". It won't return until the user hits the enter key, but it otherwise works like pause(), it is standard, and it is guaranteed to work even on systems that don't support a "pause" command (which is most operating systems other than windows)

    6) It is quite obvious that you are simply trying to fix problems by guess work. Instead, try to actually read the error messages from your compiler, and work out what they mean. Sure, a compiler doesn't speak good english, but it is consistent in the reasons it complains about bad code. A little effort to understand compiler-speak will make it much easier to solve problems like this on your own.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Jun 2013
    Posts
    3
    Alright boss second week of taking this C++ course my fault I just couldn't know as much as you think I should know. Been trying to implement arrays into the project but got stuck at this error so tried a couple things to see if it would work. Haven't learned anything about vectors and the professor uses system("pause") and return 0 that's why I've been using it. Thanks for the response and criticism.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Linkx16 View Post
    I just couldn't know as much as you think I should know.
    I don't expect a beginner to know everything. But there were two obvious possibilities: you've being taught bad technique, or you're learning on your own and developing bad technique. Either way, eventually you will need to unlearn the bad habits, and replace them with better ones. The pain - to you - of doing that increases substantially as you spend more time practicing bad technique. That pain also increases as you go longer without being told you're developing bad techniques, because you're more likely to become attached to them.

    My comment about guesswork definitely stands, regardless of anything else. It is basic problem solving technique. Computers and compilers are systematic. Getting results from them requires you to be systematic. While there will always be some guesswork involved,it is best - in terms of time you spend solving problems - to be systematic where you can. One of the fundamentals is learning to interpret compiler diagnostics, simply because they provide lots of information relevant to solving problems.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    Registered User
    Join Date
    Jun 2013
    Posts
    3
    I worked out adding individual values using vectors instead of arrays but now I'm trying to subtract individual values in a vector but having problems with working that out in the loop.
    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main()
    {
        vector<double>vectorValues;
        int Size, subtraction;
        double values;
        cout << "How mny values you want to subtract: ";
        cin >> Size;
        int i = Size;
        do{
            cout << "Enter the values to be subtracted: ";
            cin >> values;
            vectorValues.push_back(values);
            i = i--;
        }while(i != 0);
    
        cout << "You want to subtract a total of two numbers: " << int(vectorValues.size()) << "\n";
    
        for(int i = 0; i < vectorValues.size(); i++)
        {
            subtraction = vectorValues[i] - vectorValues[i - 1];
            cout << vectorValues[i] << ", ";
        }
        cout << "The subtraction of these values is: " << subtraction << "\n\n"; 
    
        system("pause");
        return 0; 
    }
    By the way to show you where I got the bad techniques from: Dynamic Memory - C++ Documentation and this person C++ Tutorials - Lesson 14: Arrays and Pointers shows examples that of pointers and arrays so I was using these sources since I haven't actually learned the material.

  6. #6
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
        for(int i = 0; i < vectorValues.size(); i++)
        {
            subtraction = vectorValues[i] - vectorValues[i - 1];
            cout << vectorValues[i] << ", ";
        }
    The bold part evaluates to vectorValues[- 1] in the first iteration -> invalid index -> crash
    Kurt

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You might want to clarify what you mean by "subtracting individual values in a vector".

    The last line, printing out the value of "subtraction", only prints the difference between the last two elements of vectorValues - because it is outside the loop.

    If you're trying to print out the differences between all consecutive values, you either need to print the differences in the loop, or create an array of differences.

    And, as Zuk has pointed out, when computing differences between elements of the same array, an array with contents 2,4,3 will only produce differences 2, -1. Note the difference in number of values.

    For the reading loop, I would suggest it is simpler to do;
    Code:
        cin >> Size;
        for (i  0; i < Size; ++i)
        {
            cout << "Enter the values to be subtracted: ";
            cin >> values;
            vectorValues.push_back(values);
        }
    than a do/while loop. Yes, your do/while loop has the same effect (except for what it does to i), but is also more difficult for people to understand.

    You might want to look carefully at the names of variables, and the strings being output. The "cin >> values" statement, for example, can be interpreted (by mere mortals) as reading multiple values, rather than (as is actually the case) one.

    Similarly, since the user is being prompted - each time through the loop - to enter multiple values, s/he might think they can enter "2,3,4" whereas the code is expecting "2 3 4" (with whitespace, not commas, between values). If the user does that, the results will not be what is expected.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Linkx16 View Post
    By the way to show you where I got the bad techniques from: Dynamic Memory - C++ Documentation and this person C++ Tutorials - Lesson 14: Arrays and Pointers shows examples that of pointers and arrays so I was using these sources since I haven't actually learned the material.
    These are advanced topics, and furthermore, somewhat outdated. They do not discuss recent additions to the language that are recommended today. They furthermore do not discuss exception safety, memory leaks or buffer overflow/underflow and out-of-bounds access.
    To be truthful, you don't need to know all of these things. They are advanced topics in themselves, which is precisely why you shouldn't be doing it the way described there, because you need to be aware of those things to use those techniques properly.
    Vectors take care of the first two. You need to be careful about the last two, however, but as you've noticed, it is much easier to getting it right than with the advanced topics.
    As an advice: Consider using the .at() member function when accessing the vector. It will throw an exception if you do something wrong, which most debuggers will catch. Many compilers will just silently let incorrectly using the index operator pass.
    For more information about arrays, see SourceForge.net: Safer arrays in Cpp - cpwiki.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 09-25-2012, 01:31 AM
  2. Passing Array To Function & Display Array Contents
    By mcertini in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2010, 01:32 PM
  3. Array passing between function
    By six in forum C++ Programming
    Replies: 2
    Last Post: 04-24-2010, 05:52 PM
  4. passing 2D array to a function
    By ashesh in forum C Programming
    Replies: 4
    Last Post: 06-09-2003, 11:16 PM
  5. 2D array passing to function
    By mkorolen in forum C Programming
    Replies: 5
    Last Post: 03-31-2002, 08:37 PM

Tags for this Thread