首页 > 解决方案 > 在 C++ 中用双指针打印字符串数组的每个字符

问题描述

该程序应打印字符串数组的每个字符。

#include <iostream>
#include <string>

using namespace std;
int main()
{
    const char* numbers[10]{"One", "Too",   "Three", "Four", "Five",
                "Six", "Seven", "Eight", "Nine", "Zero"};

    /*  This version did not work. Why?
           for (const char** ptr = numbers; *ptr != nullptr; *ptr++) {
                const char* pos = *ptr;
                while (*pos != '\0')
                    cout << *(pos++) << " ";
            }
    */
    for(unsigned int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); ++i)
    {
        const char* pos = numbers[i];
        while(*pos != '\0')
            printf("%c ", *(pos++));
        printf("\n");
    }
    return 0;
}

我知道我的代码是 C++17 和 C 的混合体(在从 C 到 C++ 的转换中nullptrcout是两个例子),但不确定第for-loop一个

for (const char** ptr = numbers; *ptr != nullptr; *ptr++)

是否正确。它出什么问题了?是否有“最佳实践”来循环遍历字符串数组(char 数组,还不是字符串对象),尤其是在这种情况下,我想捕获双指针?谢谢!

标签: c++arrayscharpointer-to-pointer

解决方案


两件事情 -

首先,在这个循环表达式中,你不需要ptr在增加它之后取消引用 - *ptr++

for (const char** ptr = numbers; *ptr != nullptr; *ptr++)
                                                  ^^

*ptr++将被分组为 - *(ptr++),这意味着,(post)incrementptr和取消引用 (post)increment 的结果。它应该是 just ptr++,因为我们需要在执行循环体后ptr指针指向数组中的下一个元素。numbers

其次,如果您的循环条件正在检查,nullptr那么循环正在迭代的数组应该nullptr作为标记来指示数组的结尾,并且您还需要增加数组的大小以调整结束标记:

     const char* numbers[11] {"One", "Too", "Three", "Four", "Five",
                              "Six", "Seven", "Eight", "Nine", "Zero", nullptr};

通过上述更改,以下循环应打印numbers数组字符串:

       for (const char** ptr = numbers; *ptr != nullptr; ptr++) {
           const char* pos = *ptr;

           while (*pos != '\0')
               cout << *(pos++) << " ";

           cout << "\n";
       }

因为,您已经在数组中添加了一个新元素numbers来标记数组的结尾,所以要小心,在第二个循环中,您正在做sizeof(numbers)/sizeof(numbers[0])的是获取数组大小并且它将给出11并且第二个循环将最终访问nullptr这将是未定义的行为. 1从结果中减去sizeof循环条件或pos != nullptr在处理之前添加检查。


推荐阅读