Pass by Pointer

Hello programmers,
The code below is a function to find the first '1' in an array. i think the ptr in firstOne() does not pass to main() and it says p in main() is not initialized. what should I change in void function when letting main remain the same?

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
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;        
		}
	}
}

int main()
    {
        int arr[6] = { 5, 11, 4, 0, 0, 7 };
        int* a;
        firstOne(arr, 6, a);
        if (a == nullptr)
        {
            cout << "no 1's in the array" << endl; 
        } 
        else
        {
            cout << "the address of the first 1 is " << a <<  endl;
            cout << "at index " << a - arr << " of the array" <<endl; 
        } 
        return( 0 ); 
    }
your code is unnecessarily complex with redundant variables like n that you don't need if you're going to write the array out by hand:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main()
{

    int arr[] = { 5, 11, 4, 0, 1, 7 };
    bool match = false;

    for (size_t i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i)
    {
        if (arr[i] == 1)
        {
            std::cout << "First 1 in the array is at location " << i + 1 << "\n";
            match = true;
            break;
        }
    }
    if(match == false)
    {
        std::cout << "No 1 in the array \n";
    }

}
> what should I change in void function when letting main remain the same?

Pass the pointer by reference
1
2
// void firstOne(int arr[], int n, int* ptr) 
void firstOne(int arr[], int n, int*& ptr ) 



Consider returning the pointer instead:
1
2
3
4
5
const int* first_1( const int arr[], int n )
{
      for( int i = 0 ; i < n ; ++i ) if( arr[i] == 1 ) return arr+i ;
      return nullptr ; // not found
}


And then, in main: const int* a = first_1( arr, 6 ) ;
Consider returning the pointer instead:

Yesterday keskiverto gave you the same advise about the same code.
Why don't you return the result?

http://www.cplusplus.com/forum/beginner/210180/
I assume you already know to use #include <iostream> and using namespace std; if you do not want to use std::cout during your code.

An easier way is having a for / while loop to go through the indexes and have if (arr[i] = 1){...} .
I think someone else has already wrote this in their code.

Another tip that might help, you can get the size of an array without knowing the number of elements in the set.

Ex. int size = sizeof(arr)/sizeof(int)

Good luck.

Last edited on
Topic archived. No new replies allowed.