在C++中返回一个比较的字符指针数组

Return an array of compared char pointers in C++

本文关键字:比较 一个 字符 数组 指针 C++ 返回      更新时间:2023-10-16

我在上大学,我们正在学习指针。我们的工作是输入一个字符,将其与数组进行比较,并返回一个指向数组中该字符的第一个引用的指针。但是,由于我不喜欢简单的事情,我已经问过我的老师,在数组中不止一次使用这个字符怎么样。这就是我头痛的开始。所以我有这个代码。其想法是:创建一个将输入字符与整个数组进行比较的函数,获取引用的指针并将其保存在数组中,然后返回该数组。不幸的是,它并没有像我希望的那样工作:(可能出了什么问题?

#include<iostream>
#include<cstdlib>
using namespace std;
char list [10];
int main()
{
    initialize();
    show();
    cout<<search('1');
}
void initialize()
{
    int i;
    for(i=0; i<10;i++)
    {
        list[i]='1';
    }
}
void show()
{
    int i;
    for(i=0; i<10;i++)
    {
        cout<<list[i];
    }
}
int* search(char* input)
{
    int* result[10];
    int i;
    char *temp;
    for (i=0; i<10; i++)
    {
        *temp=list[i];
        if(strcmp(temp, input) != NULL)
        {
            result[i]=i;
        }
    }
    return result[];
}

我在移动设备上,所以很遗憾我不能详细介绍,但您正在返回一个指针,指向您在函数中创建的数组,该数组在函数末尾超出了范围。

我的大规模编辑:

正如大家已经说过的,C++数组实际上只是指向数组中第一个元素的指针。因此,如果返回指向在函数作用域中创建的数组的指针,则返回指向垃圾的指针。如果我这样做,我会使用vector,但如果我被迫使用数组,我会用下面的代码。希望这能有所帮助!

#include <iostream>
#include <cstdlib>
void initialize(char* list) {
    for(int i = 0; i < 10; ++i) {
        if(i < 4) {
            list[i] = '2';
        } else {
            list[i] = '1';
        }
    }
}
void show(char *list) {
    for(int i = 0; i < 10; ++i) {
        std::cout << list[i] << ' ';
    }
    std::cout << std::endl;
}
// Note the function requires an additional argument that is a pointer
// this is how you can avoid returning a pointer
int search(char input, char* list, char* result) {
    int j = 0;
    for(int i = 0; i < 10; ++i) {
        // comparing characters can be done via ==
        if(input == list[i]) {
            *(result + j) = list[i];
            // You could use result[j], but I used this to show that
            // result really is just a pointer to the first element
            // of the array. As a result saying result[j] is the same
            // as saying I want to deference j elements past the first
            // element or *(result + j)
            ++j; // increment j
        }
    }
    // return how many elements matched
    return(j);
}
int main(int argc, char *argv[]) {
    char list[10];
    char temp[10];
    initialize(list);
    show(list);
    int size = search('1', list, temp);
    // create a dynamically sized array containing space for each match
    // because we don't know the size at compile time we must use
    // a library type or a dynamically sized array
    char *result = new char[size];
    for(int i = 0; i < size; ++i) {
        result[i] = temp[i];
        // again you could use result[i]
        std::cout << *(result + i) << std::endl;
    }
    delete[] result; // otherwise you'll get a memory leak
    return(0);
}