且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串数组传递给C ++中的函数

更新时间:2023-02-12 15:41:08

您正在使用此代码破坏内存。 4元素数组的元素位于[0..3]范围内,而不是[0..5]。传递字符串与传递int完全相同,只需确保函数参数类型正确,例如

You are corrupting memory with this code. The elements of a 4 element array lie in the range [0..3] not [0..5]. And passing strings is exactly the same as passing ints, just make sure the function parameter type is correct, e.g.
void rando1(string a[])
{
    for(int j = 0; j < 4; j++)
    {
        cout << a[j] << endl;
        cout << endl;
    }
}


现代 C ++ 可以很有表现力:



Modern C++ can be quite expressive:

#include <iostream>
#include <string>
#include <array>
using namespace std;

template <typename T, size_t N> void show_array( array <T,N> & a)
{
  for (const auto & x : a) cout << x << endl;
}

int main()
{

  array<int,3> ai = { -3 ,17, 0};
  array<string,2> as= {"foo", "bar"};

  show_array(ai);
  show_array(as);
}







更多(更多)传统方法:




A more (more) traditional approach:

#include <cstddef>
#include <iostream>
#include <string>
using namespace std;

void show_int_array(int ai[], size_t size)
{
  for (size_t n = 0; n < size; ++n)
    cout << ai[n] << endl;
}
void show_string_array(string as[], size_t size)
{
  for (size_t n = 0; n < size; ++n)
    cout << as[n] << endl;
}


int main()
{
  int ai[] = {3, -5, 7};
  string as[] = { "foo", "bar" };

  show_int_array(ai, sizeof(ai)/sizeof(ai[0]));
  show_string_array(as, sizeof(as)/sizeof(as[0]));
}





show_int_array 和 show_string_array 立即建议使用模板:





The code redundancy of show_int_array and show_string_array immediately suggests the usage of a template:

#include <cstddef>
#include <iostream>
#include <string>
using namespace std;

template <typename T> void show_array(T a[], size_t size)
{
  for (size_t n = 0; n < size; ++n)
    cout << a[n] << endl;
}

int main()
{
  int ai[] = {3, -5, 7};
  string as[] = { "foo", "bar" };

  show_array(ai, sizeof(ai)/sizeof(ai[0]));
  show_array(as, sizeof(as)/sizeof(as[0]));
}





'极简主义'方法



'Minimalist' approach

#include <iostream>
#include <string>
using namespace std;

int main()
{
  int ai[] = {3, -5, 7};
  string as[] = { "foo", "bar" };

  for (auto x : ai) cout << x << endl;
  for (auto s : as) cout << s << endl;
}