Cizel
Cizel

Reputation: 69

Pointer Variable to Locate the zero in the array

I am trying to make a code that tries to scan over an array for '0' using a pointer variable and then setting the address to that of the space in the array that has '0' in it. Unfortunately, my program is returning 10 as the value and 0 as an index. I would really appreciate any input to help me, and I'm trying to do this without changing main, so I dont think the following code is possible.

int* zerofinder(int array[], int q)
{
int* p = null;    /// default value if there isn't a 0 in the array at 
all
for (int k = q - 1; k >= 0; k--)
{
if (arr[k] == 0)      // found an element whose value is 0
{
    p = arr[k];     // change the value of p
    break;           // stop looping and return
}
}
return p;
}

Instead I think I have to use

void zerofinder(int array[], int x, int* p); function to change the pointer? 

Upvotes: 0

Views: 109

Answers (3)

gog
gog

Reputation: 1377

This looks like a homework / test / quiz.

The answer to this quiz is: this can't be done without changing the main function.

Why?

As others have already told you, you need to change the findLastZero signature, either changing the p parameter type as int*& or int**, or return an int* from the function. If you don't change the findLastZero signature (and the main), the findLastZero function has no way to change the outer ptr variable.

Upvotes: 1

john
john

Reputation: 87997

The problem is that you don't return the value you want from the function

int* findLastZero(int arr[], int n)
{
int* p = nullptr;    /// default value if there isn't a 0 in the array at all
for (int k = n - 1; k >= 0; k--)
{
    if (arr[k] == 0)      // found an element whose value is 0
    {
        p = &arr[k];     // change the value of p
        break;           // stop looping and return
    }
}
return p;
}

and

ptr = findLastZero(nums, 6);

Sometimes newbies think that pointers are something special, but pointers are values too, and obey the usual C++ rules about pass-by-value. If you pass a pointer to a function then changing the value of that pointer inside the function has no effect on the value outside the function, just like any other type.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206707

You pass the pointer by value.

Then you change where the pointer points to but that only modifies the local copy. It does not change the value of the pointer in the calling function.

You can resolve the problem using one of the following two approaches.

  1. Pass the pointer by reference.

    void findLastZero(int arr[], int n, int*& p);
    
  2. Return the pointer from the function.

    int* findLastZero(int arr[], int n);
    

    This will change how you call the function. Instead of using:

    int* ptr;
    ptr = &nums[0];
    findLastZero(nums, 6, ptr);
    

    you can use:

    int* ptr = findLastZero(nums, 6);
    

Upvotes: 1

Related Questions