linux-sysprog · beginner · ~15 min

Length of an argv vector

Walk a NULL-terminated pointer array.

Challenge

The exec family receives arguments as a NULL-terminated array of string pointers (argv). Count how many arguments it holds.

Task

Implement int argv_len(const char *const *argv) that returns the number of entries before the terminating NULL pointer.

Input

  • argv: array of char *, terminated by a NULL pointer.

Output

The count of non-NULL entries.

Example

argv_len({"ls", "-l", "/tmp", NULL})   ->   3
argv_len({NULL})                       ->   0

Edge cases

  • First entry is NULL: return 0.

Input format

argv: NULL-terminated array of string pointers.

Output format

Number of entries before the NULL terminator.

Constraints

The array is always NULL-terminated.

Starter code

#include <stddef.h>

int argv_len(const char *const *argv) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.