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

标签 c

在下面的示例中,如果我在 print_and_modify 函数中取消注释 matches[1] 和 matches[2] 的打印,它将失败(非法指令:4 在我的 Mac OS X 特立独行者上)。

令我困惑的是为什么 matches[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。

最佳答案

它是运算符优先级:[]* 有更高的优先级,所以你需要强制要求的优先级:

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

Demo.

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

关于c - 将指针传递给字符串指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32343398/

相关文章:

c - 全局指针引用的局部变量

c - strcat函数中 "\n"和 '\n'有什么区别?

c - 如何从共享库的文本部分获取偏移量和数据?

java - 将 Java 代码翻译为 C

c - TCP 服务器 - 从 "Too many open files"恢复

c++ - 表示小于 1 的最大 float

c++ - 如何排除部分输入被解析?

字符到 C 中的 2 的补码

c - epoll:它会悄悄地删除 fds 吗?

将 2 位数年份转换为 4 位数年份