returning an array from a function?

I have an exercise that seems to be worded poorly, would like some opinions:

"Write a function that finds the first occurrence of a value in a two-dimensional array. Return an int array of length 2 with the row and column, or null if the value was not found.

I don't believe you can return an array from a function, so should i assume that they are asking me to modify an array of size 2 that i pass into my function as an attribute? For example something like this:

int distinct_elements(int array[][COLUMN], int row_size, int value, int pos[])
{
insert code here...
}
Last edited on
You can return a dynamic array like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
int* distinct_elements(int array[][COLUMN], int row_size, int value)
{
  int row = // your logic
  int col = // your logic
  if (!found)
    return nullptr;

  int *retval = new int[2];
  // retval[0] = row;
  // retval[1] = col;

  return retval;
}
Dont' forget to delete the array(retval) in your calling function
The sad thing here is that the assignment is teaching you to be a bad programmer.

I think Thomas1965 has the prototype that you're looking for. But any time you return a raw pointer, you invite a bug. How long is the pointed-at data valid? Does it have to be deleted? If so, by whom? These are issues that the caller MUST understand and follow. So in the real world, be sure the document this stuff.

It's better to write a function like this as:
bool distinct_elements(int array[][COLUMN], int row_size, int value, int result[2]);
Although you still have to make clear whether result is modified when it returns false.

or
unique_ptr<int[2]> distinct_elements(int array[][COLUMN], int row_size, int value);

or
1
2
// return vector is empty if value not found
vector<int> distinct_elements(int array[][COLUMN], int row_size, int value);


All of these alternatives make the raw pointer problems go away.
Topic archived. No new replies allowed.