Exception when printing out values of pointers

Hey, I wrote this function that finds all the repeated values in an array and returns an array of all the pointers of these values. For some reason this function is not working in the main side. I tested and printed all the values during the function and it works with no problem. Can anyone help please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int** findAll(int value, int numbers[], int length, int& numFound){
		int* temp[100];
		numFound = 0;

		for (int i = 0; i < length; i++) {
			if (numbers[i] == value) {
				temp[numFound] = &numbers[i];
				numFound++;
			}
		}
			return temp;
	}

  //in main
  int **result = findAll(val, array, sz, szAll);
  for (int i=0; i<szAll; ++i) {
    cout << i << ": " << *result[i] << " at " << result[i]-array << '\t';
  }
  cout << endl;
Last edited on
int* temp[100];
You should not return the address of a local variable, they simply destroy itself when the function returns.
So I have to receive an array and use that or is there another way with the current method?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int*> findAll(int value, int numbers [], int length) 
{
    std::vector<int*> locations;

    int* end = numbers + length;
    int* cur = numbers;

    while ((cur = std::find(cur, end, value)) != end)
        locations.push_back(cur++);

    return locations;
}

int main()
{
    const std::size_t sz = 10;

    int array[sz] = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
    int val = array[0];

    std::vector<int*> result = findAll(val, array, sz);

    for (std::size_t i = 0; i < result.size(); ++i)
        std::cout << i << ": " << *result[i] << " at " << result[i] - array << '\t';

    std::cout << '\n';
}
Topic archived. No new replies allowed.