字符指针数组

5
我遇到了有关数组指针的问题。我已经在Google上查找过,但是目前我的尝试都是徒劳无功的。
我想做的是:我有一个char name[256]。我会有10个这样的数组。因此,我需要通过指针来跟踪它们每一个。
尝试创建指向它们的指针。
int main()
{
    char superman[256] = "superman";
    char batman[256] = "batman";
    char catman[256] = "catman";
    char *names[10];
    names[0] = superman;
    names[1] = batman;
    system("pause");
    return 0;
}

我该如何遍历一个指针数组?


你能更具体地说明“获取”值的方式吗?cout << names[0] << endl;将会输出 Superman - Dominic Cooney
cout << names[i] 可以工作。你想要实现什么? - atzz
5个回答

8

names[0]是一个指向你存储在names[0]中的任何内容的char*(在本例中是指向你的superman数组中第一个元素的指针),因此,你猜测例如cout << names[0] << endl;是正确的。

如果你想遍历该数组,你需要知道何时停止,以便不会遍历尚未初始化的指针-如果你知道已初始化了其中的2个指针,则可以执行例如:

for(int i = 0; i < 2 ; i++) {
  std::cout << names[i] << std::endl;
}

作为一种替代方案,可以在您初始化的最后一个元素之后放置一个NULL指针(确保有足够的空间放置该NULL指针),例如:

names[2] = NULL;
for(int i = 0; names[i] != NULL ; i++) {
  std::cout << names[i] << std::endl;
}

8
为什么不使用字符串和字符串向量来存储名称? 示例:
#include <string>
#include <iostream>
#include <Vector>

//using namespace std;

int main(void) {
    std::string superman = "superman";
    std::string batman = "batman";
    std::vector<std::string> names;
    names.push_back(superman);
    names.push_back(batman);
    for (unsigned int i = 0; i < names.size(); ++i) {
        std::cout << names[i] << std::endl;
    }
    char c; std::cin >> c;
}

1
+1 C++ 需要一个类似于 Python 的 "Pythonic" 的词。这是用 C++ 的方式来做的。 - BlueRaja - Danny Pflughoeft

3
char *names[] = { "superman", "batman", "whatever", NULL };

...

for (int i = 0; names[i] != NULL; i++)
    printf("%s\n", names[i]);

他可能不想使用向量,因为他可能在使用C而不是C++。
编辑:我看到他标记了C++。

1

使用任意固定长度数组来操作字符串是完全不可取的。在我的公司,这种代码将被视为非法,毫无疑问。 这种做法正是大多数安全漏洞的根源,也是使得使用这种代码的C/C++极易受到攻击的原因。 我强烈推荐从“Oops”中采用C++解决方案。


0

首先尝试使用std::string,这将使您免受内存分配和释放问题的困扰。
其次,使用std::vector<string>,它会根据需要动态扩展。

如果您必须使用char *,则需要一个指向char *的指针数组。
声明如下:

char * array_of_C_strings[10]; // 定义一个包含10个指向char *的指针数组。

如果字符串长度固定:

char array_of_fixed_length_C_strings[10][256]; // 包含10个最大长度为256的C-Strings的数组。

赋值:

char hello[32];
strcpy(hello, "Hello");
array_of_C_Strings[0] = hello;  // Note: only pointers are copied
strcpy(array_of_fixed_length_C_Strings[2], hello);  // Copy actual content of string.

使用 std::stringstd::vector<std::string>

std::string hello = "hello";
std::vector<std::string> string_container;
string_container.push_back(hello);
string_container.push_back("world!");
std::cout << string_container[0]
          << ' '
          << string_container[1]
          << "\n";

使用std::stringstd::vector的示例看起来比char *数组更简单,但这只是我的观点,可能因人而异。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接