gpt4 book ai didi

c++ - 使用指针数组的函数

转载 作者:行者123 更新时间:2023-11-30 03:48:48 26 4
gpt4 key购买 nike

我的 C++ 作业中有这个问题。

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.

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

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

}

有人可以告诉我我的错误或者告诉我我是否正确地解决了这个问题?

谢谢

最佳答案

这在您的代码中是不正确的:

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

关于c++ - 使用指针数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com