Search code examples
cglib

How to iterate over a char** without knowing its length


The GLib library gives me a char** without any length. How do I iterate over it, printing every string in the array?

I've tried the following code but it only gives me the first string, even though the array contains multiple strings.

#include <stdio.h>
#include <glib.h>

static gchar** input_files = NULL;

static const GOptionEntry command_entries[] = {
        {"input", 'i', G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING_ARRAY, &input_files, "Input files", NULL},
        {NULL}
};

int main(int argc, char **argv) {
    GOptionContext* option_context;
    GError* error;

    option_context = g_option_context_new(NULL);
    g_option_context_add_main_entries(option_context, command_entries, NULL);
    if (!g_option_context_parse(option_context, &argc, &argv, &error)) {
        g_printerr("%s: %s\n", argv[0], error->message);
        return 1;
    }
    g_option_context_free(option_context);

    if (input_files) {
        for (int i = 0; input_files[i]; i++) {
            printf("%s", input_files[i]);
        }
    }
}
$ ./a.out -i One Two Three
One

Solution

  • From the GLib documentation

    G_OPTION_ARG_STRING_ARRAY

    The option takes a string argument, multiple uses of the option are collected into an array of strings.

    (emphasis mine). You have to use the option multiple times to get multiple strings in the array.

    ./a.out -i One -i Two -i Three