找到二维字符串数组中的字符串数

时间:2015-04-17 09:10:25

标签: c++ arrays string

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

我关注this

但如果我将其传递给函数,则不起作用。

这是我试过的代码

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

2 个答案:

答案 0 :(得分:8)

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

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

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

在C ++中考虑使用std::vector<std::string>>替代。

答案 1 :(得分:1)

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

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

  

我无法修改给定的函数原型

嗯,那很不幸。然后你必须采取一些技巧。最简单的解决方法是将长度存储在全局变量而不是函数参数中。

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

相关问题