Search code examples
c++pointersglfw

How to Loop Through a const char**?


I have a const char** called glfwNames which holds the C version of a string array of the required GLFW library extensions. Would it be possible to loop through either the const char* (string), or the individual characters of the string separated by '\0'?

    const char** glfwNames = glfwGetRequiredInstanceExtensions(&glfwCount)

    for (const char** name = glfwNames; *name; ++name)
    {
         slog("GLFW Extensions to use: %s", *name);
    }

This is what I've attempted from one of the answers, and the return value of

glfwGetRequiredInstanceExtensions

is an array of extension names, required by GLFW http://www.glfw.org/docs/latest/group__vulkan.html#ga1abcbe61033958f22f63ef82008874b1


Solution

  • If glfwNames is nullptr-terminated:

    #include <cstdio>
    
    int main()
    {
        char const *glfwNames[] = { "foo", "bar", "baz", nullptr };
        for (char const **p = glfwNames; *p; ++p)
            std::puts(*p);
    }
    

    If you *know* the number of strings:

    std::uint32_t glfwCount;
    const char** glfwNames = glfwGetRequiredInstanceExtensions(&glfwCount)
    
    for (std::uint32_t i{}; i < glfwCount; ++i)
    {
         slog("GLFW Extensions to use: %s", glfwNames[i]);
    }
    

    To also loop through the individual chars:

    for (std::uint32_t i{}; i < glfwCount; ++i)
    {
         for(char const *p{ glfwNames[i] }; *p; ++p)
             std::putchar(*p);
    }