Inputting an array in to a function or returning an array? (C++)

In summary, you wrote a function to add one integer to another, but when you tried to use it in your main() function it gave you a compiler error. However, you are not sure what the first function is supposed to be doing and you want to know if there is a way to make it work.
  • #1
Zurtex
Science Advisor
Homework Helper
1,120
1
I recently came up with a bit of a mathematical problem for myself and decided I needed a bit of code to help me. My understanding of C++ is pretty basic and I seem to have found myself stuck mixing arrays and functions.

I wrote the function:

Code:
int worko (int c[], int tri)
{
    //turns the array into the number it represents
    int ans = 0;
    int i;
    for (i=0; i < tri; i++)
    {
        ans = ans + 2^c[i]*(i+1);
    }
    return ans;    
}

But in my main() the line:

Code:
int test = worko(poss[],tri);

Where poss[] is an array of length tri and tri is some integer, returns the compiler error:

68 C:\Documents and Settings\Administrator\My Documents\sillyproblem.cpp expected primary-expression before ']' token

Any ideas?

Also I want to write a function which goes something like:

Code:
int addone[] (int d[], int tri, int log)
{
    d[0] = d[0]+1;
        int j;
        for (j=0; j < tri; j++)
        {
            if (d[i] > log)
            {
                d[j]=0;
                d[j+1]++;
            }
        }
return d[];
}

But C++ seems to have no concept of returning arrays:frown:, any idea what I need to be looking at to get around this? Thanks for any help at all.
 
Technology news on Phys.org
  • #2
You almost surely want to be using std::vector instead of ordinary arrays.


But if you insist on using ordinary arrays, then they cannot be passed as a return value -- you have to pass them as arguments to your function 'by reference', so the function can modify them in place.

Also, you seem to misunderstand the syntax of ordinary arrays. [] is a decoration used to describe the type when declaring a variable: it is not part of the name of the variable.


By the way, I'm not sure exactly what the first function is supposed to be doing... but allow me to remind you that ^ is not exponentiation: it is bitwise exclusive-or.
 
  • #3
Thanks! I've not programed in C++ in about 2 years. I did forget about ^ (goes and looks up what the exponential is).

I have absolutely no insistence in using standard arrays, I'll go and look up whatever "std::vector" is :smile:.



P.S The idea of the first function is that it takes the array [x1,...,xn] and calculates the value 1*2x1 + 2*2x2 + ... + n*2xn.

I'm trying to work out the set of integers which can't be represented in that form, where {xi}i = 1,...,n is a monotonically decreasing sequence of non-negative integers. For example, 5 and 11 can't be represented in that form, I have a good idea which numbers in general can't be represented in that form but I wanted to quickly write something into the computer to confirm my idea for a few more integers.
 
  • #4
Look up C-style arrays and pointers. I recommend the chapter in

The C Programming Langauge has often been cited as a model for technical writing, due to the book's clear presentation and concise treatment.

You will trip up often working with C-style arrays (what you are using) until you actually understand what they really represent. They are not atomic vectors, things you can pass around as a unit or assign values to. They are regions of memory space, in which their contents are stored. They are intimately connected with the memory pointer, which has how you reference memory in C and C++. What you pass around when you manipulate arrays is not a vector or a set, but a memory pointer.

This is not easy or intuitive, because C and C++ are "low level" languages - they are designed for system programming that closely reflects the HARDWARE, not like "high level" languages, which use natural concepts suitable for HUMANS. You will probably find things much easier in a high level language like Python, where lists (superficially like arrays) are first-class objects, which you can directly return from functions and so on. Also, the syntax is much more straightforward, and you can program interactively in an interpreter.

python-logo.gif

(recommended!)

If you stick with C++, an alternative is what Hurkyl mentioned, the standard template library containers (STL = standard template library), which attempts to bring abstractions like vectors (std::vector) and lists to C++. But you certainly find things easier in Python.

I did forget about ^ (goes and looks up what the exponential is).

In C++, you will need to include something like <cmath> which has as exp() function. Python for contrast has a built-in exponentiation operator (it is **).
 
Last edited by a moderator:
  • #5
As a preview: in C++, to write a function which takes an array, and returns the array scaled by a constant factor, the type signature would look like:

Code:
float* scale(float scalefactor, float arr[], int length);

Where float* is a pointer type. And the implementation would look like:

Code:
float* scale(float scalefactor, float arr[], int length) {
   float* ans = new float[length];
   for (int i = 0; i < length; i++) {
      ans[i] = scalefactor * arr[i];
   }

   return ans;
}

where 'new' is how you can dynamically create an array of variable size - it is manual memory allocation. And you could use it like:

Code:
float arr[] = {1,2,3};
float* ans = scale(10, arr, 3);
std::cout << ans[0] << " " << ans[1] << " " << ans[2] << "\n";
// prints "10 20 30"

Note that the function calling convention for an array or pointer argument does not include either the '[]' or '*' - those are for type declarations (and other stuff). This:

Code:
float* ans = scale(10, arr, 3);

Not this:

Code:
float* ans = scale(10, arr[], 3);

C++ is byzantine, and this isn't even the start of it.
 
  • #6
I usually pass arrays around with pointers...just make sure they are in sequential memory addresses when allocating the memory like so:

const int nTri = 6;
int rgC[nTri] = { 0 };
int nRes = worko(rgC, nTri);
 

1. How do I input an array into a function in C++?

In C++, you can use either pass-by-value or pass-by-reference to input an array into a function. To pass-by-value, you would declare the function parameter as an array, and then use the array index notation to access the elements inside the function. To pass-by-reference, you can use pointers as the function parameters and dereference them to access the array elements.

2. Can I return an array from a function in C++?

Yes, you can return an array from a function in C++. To do this, you need to declare the return type of the function as an array and then use the return statement to return the array. Keep in mind that arrays in C++ are passed by reference, so returning an array from a function can be more efficient than passing it as a parameter.

3. How do I pass a dynamic array into a function in C++?

To pass a dynamic array into a function in C++, you can use either pass-by-value or pass-by-reference as described above. However, since dynamic arrays have a variable size, using pass-by-reference can be more efficient as it avoids copying the entire array into the function.

4. Can I modify an array inside a function and have the changes reflected outside the function?

Yes, you can modify an array inside a function and have the changes reflected outside the function by using pass-by-reference. This allows the function to directly access and modify the original array in memory, rather than creating a copy of the array.

5. Are there any limitations to inputting or returning arrays in C++ functions?

One limitation to keep in mind when inputting or returning arrays in C++ functions is that arrays cannot be passed by value if they are too large. This is because arrays are stored in contiguous blocks of memory, and passing them by value would require copying the entire array, which can be inefficient and may cause memory issues for very large arrays.

Similar threads

  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
23
Views
1K
  • Programming and Computer Science
Replies
20
Views
1K
  • Programming and Computer Science
Replies
1
Views
943
  • Programming and Computer Science
Replies
22
Views
2K
  • Programming and Computer Science
Replies
13
Views
4K
  • Programming and Computer Science
Replies
17
Views
1K
Back
Top