Mohan
Mohan

Reputation: 317

Passing a pointer to array of string pointers

In the example below if I uncomment the printing of matches[1] and matches[2] in the print_and_modify function it fails(Illegal instruction: 4 on my Mac OS X mavericks).

What confuses me is why matches[0] works fine ? Any help is greatly appreciated.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void print_and_modify(char ***matches) {
  printf("%s\n", *matches[0]);
  /* printf("%s\n", *matches[1]); */
  /* printf("%s", *matches[2]); */
}

int main(int argc, char **argv)
{

  char **matches;

  matches = malloc(3 * sizeof(char*));

  matches[0] = malloc(10 * sizeof(char));
  matches[1] = malloc(10 * sizeof(char));
  matches[2] = malloc(10 * sizeof(char));

  char *test1 = "test1";
  char *test2 = "test2";
  char *test3 = "test3";

  strncpy(matches[0],test1,5);
  strncpy(matches[1],test2,5);
  strncpy(matches[2],test3,5);
  print_and_modify(&matches);

  printf("======\n");
  printf("%s\n", matches[0]);
  printf("%s\n", matches[1]);
  printf("%s\n", matches[2]);
}

Please excuse the contrived example. I am trying to learn some C.

Upvotes: 1

Views: 36

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

It's operator precedence: [] has higher precedence than *, so you need to force the desired precedence:

void print_and_modify(char ***matches) {
    printf("%s\n", (*matches)[0]);
    printf("%s\n", (*matches)[1]);
    printf("%s", (*matches)[2]);
}

Demo.

Note that you do not need to pass a triple pointer, unless you wish to modify the allocated array itself. If you pass a double pointer, you would be able to modify the content of the individual strings, and also replace strings with other strings by de-allocating or re-allocating the char arrays.

Upvotes: 1

Related Questions