Double pointers in C - a detailed example

Let ptr be a pointer to a char *. This kind of variable, a pointer to a pointer, is often encoutered in argument parsing as an example.

You can pass shell arguments to a C program by updating main(void):

int main(int argc, char **argv)
{
  return (EXIT_SUCCESS);
}

Why is argv a char **? Because it is a pointer to an array of pointers, each holding the memory location of a string. In our case, if we compile this program and run it using:

$ cc test.c -o test.bin
$ ./test.bin I am a potato

the content of argv will be:

argv = {"I", "am", "a", "potato"};

As for the argc argument, in contains an integer representing the number of values in argv, which means you have to iterate from 0 to argc-1

I like to parse the arguments myself. Here is a parsing routing from my raytracer:

raytracer/source/args.c:

void        parse_args(t_args *args, int argc, char **argv)
{
  int       i;

  i = 1;
  while (i < argc)
    {
      if (!strcmp(argv[i], "--coords") && ((i + 3) < argc))
        {
          args -> sphere_coords.x = atoi(argv[++i]);
          args -> sphere_coords.y = atoi(argv[++i]);
          args -> sphere_coords.z = atoi(argv[++i]);
        }
      else if (!strcmp(argv[i], "--radius") && ((i + 1) < argc))
          args -> radius = atoi(argv[++i]);
      else
        {
          my_puts("Syntax: raytracer [--coords x y z] [--radius r]\n");
          exit(FAILURE);
        }
      ++i;
    }
}

Please note that t_args is defined as:

typedef struct s_args t_args;
struct      s_args
{
  t_vector  sphere_coords;
  double    radius;
};

(the args structure is initialized in another routine)

Anyway, notice how I am iterating through the char **, I am accessing every pointer just like I would with a normal array. I’m bad at explaining pointers, but just consider a pointer a variable that contains a number, generally 8 bytes long, and represents the memory location of another variable.