将指针传递给字符串指针数组

时间:2015-09-02 01:41:29

标签: c

在下面的示例中,如果我取消注释匹配[1]的打印并且匹配print_and_modify函数中的[2]则失败(非法指令:我的Mac OS X小牛上的4)。

令我困惑的是为什么匹配[0]工作正常?非常感谢任何帮助。

#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]);
}

请原谅人为的例子。我正在尝试学习一些C.

1 个答案:

答案 0 :(得分:1)

它是运算符优先级:[]的优先级高于*,因此您需要强制所需的优先级:

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

Demo.

请注意,除非您希望修改已分配的数组,否则不需要传递三重指针。如果传递双指针,则可以修改单个字符串的内容,还可以通过取消分配或重新分配char数组来将字符串替换为其他字符串。

相关问题