Adam
Adam

Reputation: 43

Function which uses array of pointers

I have got this question on my c++ homework.

Write and test the function location that takes, as shown below, a table of pointers to integers p, the size of such a table n and an integer value x.

                      int* location (int* p [ ], int n, int x);

location searches the set of integers pointed at by the table of pointers p for a match to the value of x. If a matching integer is found, then location returns the address of that integer, NULL otherwise.

I'm not sure that I fully understand the question. However, I tried to solve it but I got error(the program crashes). Here is my code.

#include<iostream>
using namespace std;
int* location (int* p [ ], int n, int x);
void main(){
    int arr[3]={1,2,3};
    int *ptr=arr;
    int *address= location (&ptr, 3, 2);
    cout<<&arr[3]<<" should be equal to "<<address<<endl;
}
int* location (int* p [ ], int n, int x){
    for(int i=0; i<n; i++){
        if(*p[i]==x){return p[i];}
    }

    return NULL;

}

Can someone please show me my mistake or tell me if I'm solving the question correctly?

Thanks

Upvotes: 1

Views: 81

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

This is not correct in your code:

cout<<&arr[3]<<" should be equal to "<<address<<endl;

You are accessing array element with index 3, however, maximum index you can access in your case is 2. Also, there is alternative solution below.

Also the way you are passing pointer to a pointer to your location function (and also using it) is wrong. Because for example you haven't declared array of pointers to integers in the first place.


You can try to read somewhere a bit more on the notion of array of pointers in C++, in order to better understand the example below.

#include <iostream>

using namespace std;
const int MAX = 3;

int* location (int* p [ ], int n, int x);

int main ()
{
   int  var[MAX] = {10, 100, 200};

   // Declare array of pointers to integers
   int *ptr[MAX];

   for (int i = 0; i < MAX; i++)
   {
      ptr[i] = &var[i]; // Store addresses of integers
   }

   int *x = location(ptr, MAX, 100); // Now you have pointer to the integer you were looking for, you can print its value for example
   if(x != NULL) cout<<*x;

   return 0;
}

int* location (int* p [ ], int n, int x)
{
  for(int i = 0; i<n; i++)
  { 
     if(*p[i] == x) return p[i];
  }

 return NULL;
}

Upvotes: 2

Related Questions