1

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.

3
  • 2
    If you're learning C, as soon as you see *** RUN AWAY. Commented Sep 2, 2015 at 1:43
  • How else would you pass a pointer to a *char[] to a function ? Commented Sep 2, 2015 at 1:44
  • 3
    use (*matches)[0],(*matches)[1]and (*matches)[2] instead of. Commented Sep 2, 2015 at 1:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

[] is called subscript, * is called dereference.
@dasblinkenlight - I do plan to modify the allocated array. I would like for the function to be able to increase the size of the array. Additionally I would also like for print_and_modify to be able to initialize it if its not been initialized yet. Thanks for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.