在2D字符串数组中查找字符串数

find the number of strings in 2D array of strings

本文关键字:字符串 查找 数组 2D      更新时间:2023-10-16

给定一个字符串数组,我需要找出其中的字符串数。

我跟踪了这个

但是如果我把它传递到一个函数中,这是不起作用的。

这是我试过的代码

#include<string>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int f1(char* input1[])
{
string s="";
cout<<sizeof(input1)<<endl; //print 4
cout<<sizeof(char*)<<endl;  //print 4
int l=sizeof(input1) / sizeof(char*);
//giving l=1 here but should be 8
}
int main()
{
char *str2[]={"baba","sf","dfvf","fbfebgergrg","afvdfvfv","we","kkhhff","L"};
int l=sizeof(str2) / sizeof(char*);
cout<<l<<endl; //print 8
cout<<sizeof(str2)<<endl; //print 32
cout<<sizeof(char*)<<endl; //print 4
f1(str2);
}

sizeof(char*)为您提供char*指针的大小(在您的系统中为4)。

sizeof(str2)将为您提供数组str2的大小。共有8个元素,每个元素都是一个指针类型。因此,系统的总大小为8 x 4=32。

要获取字符串的长度,请使用strlen

请考虑将std::vector<std::string>>作为C++中的替代方案。

如果你只有一个指向数组的指针,你就无法知道数组的长度。而且你只有指针,因为你无法按值传递数组。传递给函数的数组将自动衰减为指针,参数类型char* foo[]等效于char** foosize_of没有帮助,因为它只会告诉指针本身的大小。

将长度作为参数传递给f1。或者更好的是,使用std::vectorstd::array

我无法修改给定的功能原型

很不幸。那你就得耍花招了。最简单的解决方法是将长度存储在全局变量中,而不是函数参数中。

另一种可能是终止值。例如,始终以nullptr结束数组,并且从不允许其他元素具有该值。与c字符串以null字符终止的方式相同。然后,当遇到nullptr时,可以停止迭代数组。但我认为您也不能修改数组。