Quick C++ Problem - Combining Functions for Array Output

  • Thread starter Zurtex
  • Start date
  • Tags
    C++
In summary, NateTG's code which uses "ans" to create an array of size 2 always returns the first element, while the code which uses "ans[2]" returns an array of size 1, because "ans[2]" defines an array of size 2. When trying to use "ans[0]" to return the first element, you get an error.
  • #1
Zurtex
Science Advisor
Homework Helper
1,120
1
I'm just finishing off my C++ project and I decided when looking at two functions that they would be far more efficent as one function (because they are always used together and as it was it repeats the same code twice).

Now I wanted my output as an array so I could called on the two needed numbers.

So my test code went something like this:

CTenK split_power_two(CTenK number);

CTenK split_power_two(CTenK number)
{
CTenK Answer[2];
Answer[1]=One;
Answer[2]=Two;
return Answer[2];
}

Which didn't work at all of course and only returned Two. I've also tried thinks like:


CTenK[2] split_power_two(CTenK number);

CTenK[2] split_power_two(CTenK number)
{
CTenK Answer[2];
Answer[1]=One;
Answer[2]=Two;
return Answer[2];
}

And I get some horrible errors for that.

(Note CTenK us just a class we made up and are using)

Any help would be fantastic.
 
Physics news on Phys.org
  • #2
If you want to return the array, you need to use
"return Answer"
When you put the []'s at the end, it dereferences them.

In C, (and I assume C++) arrays and pointers are very similar. Effectively,
Answer[2]
and
*(Answer+2)
are the same thing, if that makes any sense at all.

P.S. C is also zero-based, so you're doing something weird unless there's a value assigned to Answer[0].
 
  • #3
NateTG is correct. Also, you will have to change your return type from CTenK to CTenK* in order to use the return value as an array in your calling function. Try:

CTenK* split_power_two(CTenK number)
{
CTenK Answer[2];
Answer[0]=One;
Answer[1]=Two;
return Answer;
}

-Dale
 
  • #4
simpler way to think about is to
type define CTenK*

"typedef CTenK* CTenKArray" which may clarify the confusion.
or I'm pretty sure you could do
"typedef CTenK[2] CTenKArray2D"
remember an array should be understood as a ptr to the first element of the array

also NateTG
Answer[2]
and
*(Answer+2)
is that correct? i thought it would be *(Answer+1)
------------
 
  • #5
I like the typedef, it does make it more readable and convenient. Particularly for newer programmers who may not be comfortable with arrays/pointers.

neurocomp2003 said:
also NateTG
Answer[2]
and
*(Answer+2)
is that correct? i thought it would be *(Answer+1)
------------
NateTG is correct here. The "X[n]" operator is just shorthand for the "*(X+n)" syntax. The confusion is probably because for an array of length 2 both "Answer[2]" and "*(Answer+2)" would be out of bounds and would typically lead to nasty run-time errors.

-Dale
 
  • #6
Thanks, but can't say I understood much of that sorry, but I got the general jist and this code produced no compile errors:

CTenK* split_power_two(CTenK number)
{
CTenK *Answer[1];
*Answer[0]=One;
*Answer[1]=Two;
return *Answer;
}

However I am now stumped how to actually use it, certainly the code:

main ()
{
CTenK dummy=One;
cout << split_power_two(dummy)[1] << "\n";
system("Pause");
}

Just crashes.
 
  • #7
DaleSpam: i was under the impression that an array works as
Answer[2] -> *(answer+0) is the first element and *(answer+1) is the 2nd element?

Zurtex:
"CTenK *Answer[1]" defines a pointer to an array of one element.
...exactly what are you trying to do? if you don't mind me asking...
anyways..
line 1: CTenK* split_power_two(CTenK number)
is this correct-> You are inputing 1 TenK in and returning an array of TenK?

line2: should either read: CTenK* ans; or CTenK ans[2];...
the first is an undefined size, that points to the first element.
If you choose to use this method you will need to further "create" or allocate memory for a desired size.
[A] ans=new CTenK[2];
ans=malloc(2*sizeof(CTenk)); //may be wrong syntax haven't used malloc in along while..

The 2nd declaration method is probablly easier.
CTenK ans[2]; //defining a CTenK array of size 2

line 3...*answer[0]=One; what are you tryign to achieve here?
if you're just trying to insert One into element 1(0 idx) you leave off the star*. To access an element using the array-style operator [] is simply
varname[]. IF you choose to use the star you would need to do what was given in one of the above posts: *(answer+#).
what this means is your moving your pointer along "#" of CTenK size memory blocks away from the first...and then getting the element by dereferencing using *. Its easier to understand with the operator [].

so "ans[#]=value;"

line 5: if I'm correct you are only returning the first element.
because *answer is the first element...BUT to return the whole array
return answer.
------------------
NOTE: everytime you do varname[#] you are accessing the element at # index, if you've allocated that many memory blocks, either through "new", "malloc" or using "Type varname[#];"

NOTE: everytime you do *(answer+#) you are accessing #
# number of CTenK sized memory blocks away from the first.

NOTE: if you want to work with the whole array you just use the varname without any other symbols...so to return the whole array "return varname"

Hope that's not confusing.
 
  • #8
oh yeah so your code would look something like
CTenK* split_power_two(CTenK number)
{
CTenK Answer[2];
//OR CTenK* answer=new CTenK[2];
//OR CTenK* answer= malloc(2*sizeof(CTenK));
Answer[0]=One; //*(answer+1) = one; if NateTG and Dale are right.
Answer[1]=Two;
return Answer;
}
NOTE:you may need //*(answer+1*sizeof(CTenK)). my compiler was flaky with this.

main ()
{
CTenK dummy=One;
cout << split_power_two(dummy)[1] << "\n";
system("Pause");
}
//not sure if you can apply [] to the function like that but if it works i learned something new...
try CTenK* array; array= split_power_two(dummy) and
cout << array[1]; if your way doesn't work.

also printf/cout is your friend if your not sure how to use the debugger or too lazy to learn like i am ...printf every step where you think your code is going wrong.
 
  • #9
o.k, nevermind, this is FAR more complicated than I expected it to be.

All I wanted was a function where I put a number in and get an array out. Namely so I can put a number b in and get s and t out, where:

[tex]b = 2^st + 1[/tex]

The code I've written to work out t, repeats the code to work out s, as I always need both I wanted a code which did them both together.

My course doesn't go into too much detail about C++ and I've never really liked this whole pointer thing or ever seen any real use for it.

Although I do appreciate the help greatly and will read over this in more detail some other time.
 
  • #10
CTenK split_power_two(CTenK number)
{
CTenK Answer[2];
Answer[1]=One;
Answer[2]=Two;
return Answer[2];
}

you are returning Answer[2] you need to give it parameters on each answer example if(FFFF)
return ?
else
return ?
and also if CTenK Answer[2]; is an array of type CTenk then the only elements in that array you should use is 0, and 1 because in c++ the elements in the arrays begin at 0 and the last element is null if you need to use Answer[1] and Answer[2] you need to declar a 3 element array so that Answer[3] will be the null or ending character of that array not answer[2]. why it is returning 2 baffles me perhaps it is not returning properly, or something in the calling program
 
  • #11
neurocomp2003 said:
DaleSpam: i was under the impression that an array works as
Answer[2] -> *(answer+0) is the first element and *(answer+1) is the 2nd element?
Correct. To declare an array of two doubles you use:

CTenK Answer[2];

to access the first element you can use either Answer[0] or *(Answer+0) and to access the last element you can use either Answer[1] or *(Answer+1)

If you try to access the last element using either Answer[2] or *(Answer+2) you will get a runtime error.

-Dale
 
  • #12
Zurtex said:
Thanks, but can't say I understood much of that sorry, but I got the general jist and this code produced no compile errors:

CTenK* split_power_two(CTenK number)
{
CTenK *Answer[1];
*Answer[0]=One;
*Answer[1]=Two;
return *Answer;
}

However I am now stumped how to actually use it, certainly the code:
main ()
{
CTenK dummy=One;
cout << split_power_two(dummy)[1] << "\n";
system("Pause");
}
Just crashes.
Zurtex said:
o.k, nevermind, this is FAR more complicated than I expected it to be.
All I wanted was a function where I put a number in and get an array out. Namely so I can put a number b in and get s and t out, where:
[tex]b = 2^st + 1[/tex]
The code I've written to work out t, repeats the code to work out s, as I always need both I wanted a code which did them both together.
My course doesn't go into too much detail about C++ and I've never really liked this whole pointer thing or ever seen any real use for it.
Although I do appreciate the help greatly and will read over this in more detail some other time.
Sorry that I didn't think about this when I replied the first time, but I just realized why my suggestion won't work. In C/C++ arguments are typically passed by value and memory is reclaimed when a variable goes out of scope. So, if you take my suggestion:

CTenK* split_power_two(CTenK number)
{
CTenK Answer[2];
//...
return Answer;
}

this is what will happen. The program will enter split_power_two and it will allocate enough memory to hold two CTenK and Answer will be set to the address of that block of memory. At the return statement the address of the memory block will be sent to the calling function, then when control passes to the calling routine the memory will be deallocated. So, in the calling process the result will point to an invalid memory location and you will get the crashes that you saw.

You can return structs, classes, and basic types without any trouble, because those are copied by value and when they are deallocated inside the function the calling program still has the copy of the value. With the array only the pointer to the first element is copied by value and the actual data is deallocated and lost. For this reason you usually see arrays intended for output passed in the argument list as follows:

void split_power_two(CTenK number, CTenK* Answer)
{
Answer[0]=One;
Answer[1]=Two;
return;
}

You could then use it as follows:

main ()
{
CTenK dummy=One;
CTenK answer[2];
split_power_two(dummy, answer);
cout << answer[0] << "\n";
cout << answer[1] << "\n";
system("Pause");
}

Pointers are very useful, particularly in object-oriented-programming where they are pretty much essential in C++ in order to implement polymorphism. But they are very confusing for beginners and, as you have seen, they are easy to mix up even for people with experience.

-Good Luck
Dale
 
Last edited:
  • #13
ptrs are just as important in C even more some whne your passing around parameters.
 
  • #14
oh yeah isn't this in the wrong homework section
and dale you can create an array and return it because its ptrs isn't it? or atleast microsoft treats it as so.
typedef int int2[2];
typedef int* intP;
int* tp(int)
{
//int ret[2];
int2 ret;
//int* ret= new int[2];
//int* ret=(int*)malloc(2*sizeof(int));
ret[0]=1;
ret[1]=2;
return ret;
}

int main(int argc, char*argv[])
{
int* k=new int[2];
k=tp(3);
printf("%d,%d",k[0],k[1]);

return 0;
}
 
Last edited:
  • #15
Yes, neurocomp, and as you point out the key is to use "new" to dynamically allocate the memory rather than the normal static allocation.

When you allocate the memory statically then it will be deallocated as soon as you leave the scope of the function. Then in the calling scope your returned pointer will point to garbage. With dynamic allocation it won't be deallocated until you specifically call "delete". Until then you can pass it in and out of as many functions as you like.

Personally, if I always needed exactly two values I would make it a struct. E.g. CTenKPair.s and CTenKPair.t for the two numbers in the solution. Then you could return it just fine without worrying about pointers, arrays, dynamic allocation, scope, etc.

-Dale
 
Last edited:

1. How do I combine multiple functions in C++ for array output?

To combine multiple functions for array output in C++, you can use the concept of function overloading. This allows you to create multiple functions with the same name but different parameters, and the compiler will determine which function to use based on the parameters passed. You can also use the return statement to pass the output of one function as a parameter to another function.

2. Can I use arrays as parameters in C++ functions?

Yes, you can use arrays as parameters in C++ functions. You can either pass the entire array as a parameter or pass a specific element or range of elements as parameters. When passing the entire array, you need to specify the array size as well.

3. How can I print the elements of an array in C++?

To print the elements of an array in C++, you can use a loop (for loop or while loop) to iterate through the array and print each element. You can also use the array index notation to access and print specific elements of the array.

4. Is it possible to combine two arrays in C++ and output the combined array?

Yes, it is possible to combine two arrays in C++ and output the combined array. You can create a new array and use a loop to copy the elements of both arrays into the new array. Alternatively, you can use the built-in std::copy function to merge the arrays into a new array.

5. How can I ensure that my C++ program does not go out of bounds when working with arrays?

To ensure that your C++ program does not go out of bounds when working with arrays, you can use the array size to limit the loop iterations. You can also use conditional statements to check for the array boundaries before accessing or modifying elements. Additionally, you can use the std::array data structure, which provides built-in bounds checking for arrays.

Similar threads

  • Calculus and Beyond Homework Help
Replies
2
Views
893
Replies
9
Views
714
  • Programming and Computer Science
Replies
2
Views
1K
  • Calculus and Beyond Homework Help
Replies
3
Views
123
  • Calculus and Beyond Homework Help
Replies
17
Views
885
  • Engineering and Comp Sci Homework Help
Replies
21
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
754
  • Calculus and Beyond Homework Help
Replies
1
Views
282
  • Programming and Computer Science
Replies
4
Views
735
  • Programming and Computer Science
Replies
17
Views
2K
Back
Top