在C++中返回一个比较的字符指针数组
Return an array of compared char pointers in C++
我在上大学,我们正在学习指针。我们的工作是输入一个字符,将其与数组进行比较,并返回一个指向数组中该字符的第一个引用的指针。但是,由于我不喜欢简单的事情,我已经问过我的老师,在数组中不止一次使用这个字符怎么样。这就是我头痛的开始。所以我有这个代码。其想法是:创建一个将输入字符与整个数组进行比较的函数,获取引用的指针并将其保存在数组中,然后返回该数组。不幸的是,它并没有像我希望的那样工作:(可能出了什么问题?
#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);
}
相关文章:
- 如何在 c++ 中比较 2 个链表并将匹配的数据放入另一个链表中
- C++设置了一个用于排序的比较器和另一个用于唯一性的比较器
- 绘制一个对象,比较模具缓冲区的两个不同值
- 我如何将一个变量与另一个变量进行比较,例如我想如果(var1 > var2 x 1),然后执行此 c++
- 如何比较文件中包含的下一个字符
- 为 RocksDB 实现一个比较器
- 将当前多边形数据单元与下一个多边形单元格 - VTK 进行比较
- 比较最后一个字符,不区分大小写(带谓词?
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 与C++中不止一个字符进行比较
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 在数组中仅比较一个字符
- 如何将一个值与整个数组进行比较
- 如何制作一个从文件中读取密码并与用户编写的密码进行比较的 c++ 程序
- C++:将当前时间与下一个工作时间进行比较
- 我怎样才能洗牌给定大小的数组并将其与C++中另一个相同大小的数组进行比较
- 比较一个链接列表与另一个黑名单与词频列表C++
- 为什么在汇编代码中比较一个在范围内的数字时会发生分支
- 是否有一种方法可以正确地比较一个float值是否大于/小于另一个
- 比较一个向量中向量的大小,得到最大的