gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:26 24 4
gpt4 key购买 nike

在下面的示例中,如果我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com