2015-10-05 39 views
1

我的C++作业中有这个问题。使用指针数组的函数

编写和测试功能位置即发生,如以下所示,一个 表指针为整数P,这样的表n的大小和 整数值x。

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

位置搜索整数集在由指向指针 p的表的匹配来x的值。如果找到匹配的整数 ,则位置返回该整数的地址,否则返回NULL 。

我不确定我完全理解了这个问题。但是,我试图解决它,但我得到错误(程序崩溃)。这是我的代码。

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

} 

有人可以告诉我我的错误,或告诉我,如果我正确解决问题?

感谢

+0

我会说问题在于'return NULL;'。 –

+0

如下面的答案所示,您正在将一个指针传递给函数的整数数组。你需要将一个指向数组的指针数组传递给函数。 –

+0

编写'*(p [i])'或'(* p)[i]'来清除您的代码。 (根据描述,你想要第一个) –

回答

2

这是不是在你的代码正确:

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

您正在访问数组索引3,但是,最大的指数,你可以在你的情况下访问是2。此外,有下面的替代方案。

此外,您传递指向指向location函数(也使用它)的指针的方法是错误的。因为例如你没有首先声明整数指针数组。


你可以尝试的地方更多了一下阵列中的C++指针的概念,以便更好地理解下面的例子。

#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; 
} 
+1

非常感谢你<3 如果可能的话,要声明指向整数的指针数组,什么是: int * ptr = var; (int i = 0; i Adam

+0

@Adam:在你的情况下,ptr只是一个指针,而在我的情况下,ptr是指针数组,这就是为什么我建议你在该主题上多读一点来理解差异;因为你可以有整数数组,你可以有指针数组 –