Error with return type

The error I'm getting is with the return at the end. It says, "Error: return value type does not match the function type." From what I can tell the function type is int, as is dArray.

Any help in solving this problem is appreciate. Also, please try and keep you answers as simplified as possible.

Thank you!
1
2
3
4
5
6
7
8
9
10
  int Test::*AllocateArray(int size, int value){
	int* dArray = new int [size];
	
	for (int i = 0; i < size; i++){
			dArray[i] = value;
			std::cout << dArray[i] << std::endl;
	}

	return dArray;
};
dArray is a pointer and an array (it points to some memory location). A function cannot return an array as far as I know
Yes, the function type is int. However, dArray is a pointer to an array of int, there is a difference. Assuming that you want to return an array of integers, here is your function fixed:
1
2
3
4
5
6
7
8
9
10
// the ::* operator is for declaring pointer-to-member functions.
// Don't worry about, just know that for your purposes its wrong.
int* Test::AllocateArray(int size, int value) {
    int* dArray = new int[size];
    for (int i = 0; i < size; ++i) {
        dArray[i] = value;
        std::cout << dArray[i] << std::endl;
    }
    return dArray;
}


@letscode
Yes, you can return an array. Sort of. You can't return a static array as such (it degenerates into a pointer), but you can return a pointer to the first element in a row of contiguous elements (which is all that a dynamic array is, anyway). Hence us returning int*, or a pointer to an integer (which happens to be the first element of the array).
Last edited on
You can how ever return a pointer that points to the array.

I think you put the * asterisk on the wrong side of Test.

int *Test::AllocateArray(int size, int value)

*edit also don't forget to delete the allocated array with delete [] when you are done with it.
Last edited on
Initial issue solved! Thank you!

Test is the name of my class. When you write the star(*) outside of test instead of in front of "AllocateArray" what is this saying? It solved my problem, but why. What was I saying before in terms of syntax v.s. what does it say now?
Its just a return type. You can return a copy , pointer to object , reference to object. So we changed it from returning an int to a pointer to an int. After the Scope but before the function name does nothing as far as I am aware. It would almost be the same as saying int p*tr; or even in*t ptr; instead of like int *ptr;

http://www.learncpp.com/
I would suggest you read chapters 6 and 7. They talk about pointers and functions(return types).

*forgot link
Last edited on
Topic archived. No new replies allowed.