pointer error

Hello programmers,
the function below to find the first 1 of an array does not run well and has run time error.
what would be the problem?
1
2
3
4
5
6
7
8
9
10
11
12
void firstOne(int arr[], int n, int* ptr)
{
	ptr = nullptr;    
	for (int k = 0; k < n; k++)
	{
		if (arr[k] == 1)      
		{
			ptr = arr + k; 
			break;        
		}
	}
}
Last edited on
The ptr is a by value parameter. Nothing that you do to it in the function will affect the pointer of the caller.

Why don't you return the result?
If it's not clear, inside "firstOne()" int *ptr will be a new pointer which will point to the same memory area of the passed pointer, but what you do to ptr does not effect the caller pointer.
If you modified the pointed area, you could later take advantage of it from the caller function.

The following code just print out the address memory pointed and its content; hope it can give some hint.
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
32
33
34
35
36
37
#include <iostream>

void firstOne(int arr[], int n, int* ptr);

int main()
{
    int arr[] = {5, 4, 3, 6, 7, 4, 1, 8, 9, 7};
    std::cout << "main arr[] = " << (long long)arr << std::endl;
    int* ptoint = arr;
    std::cout << "main ptoint = " << (long long)ptoint << std::endl;

    firstOne(arr, 10, ptoint);

    std::cout << "\nmain ptoint = " << (long long)ptoint << std::endl;
    std::cout << "main *ptoint = " << *ptoint << std::endl << std::endl;
    return 0;
}

void firstOne(int arr[], int n, int* ptr)
{
    std::cout << "\nfirstOne arr[] = " << (long long)arr << std::endl;
    std::cout << "firstOne: ptr = " << (long long)ptr << std::endl;
//    ptr = nullptr;
    for (int k = 0; k < n; k++)
    {
        if (arr[k] == 1)
        {
            ptr = &arr[k];
            std::cout << "firstOne &arr[" << k << "] = "
                      << (long long)&arr[k] << std::endl;
            std::cout << "firstOne arr[" << k << "] = " << arr[k] << std::endl;
            std::cout << "firstOne ptr = " << (long long)ptr << std::endl;
            std::cout << "firstOne *ptr = " << *ptr << std::endl;
            break;
        }
    }
}

Topic archived. No new replies allowed.