gpt4 book ai didi

c - 如何为字符串数组创建指针?

转载 作者:行者123 更新时间:2023-11-30 18:10:45 25 4
gpt4 key购买 nike

我是 C 新手,不知道在涉及字符/字符串时如何正确传递指针/地址。我无法理解这些“字符串”,不知道如何掌握指针。

我基本上想将下面定义的数组“a”的地址传递给任意函数,但我不知道如何定义该数组的指针。

请帮助我!

我有以下代码:

void change(char** a){
a[0][0]='k'; //that should change a inside main
}

void main() {
char a[2][3];
char *tempWord;
tempWord="sa";
a[0]=tempWord;
a[1]=tempWord;
change(&a);
}

最佳答案

您有一个char[2][3]这样你就可以通过 char (*)[2][3]给您change功能。复制tempWord进入你的char[][]您可以使用strncpy 。假设我明白你想要做什么,那可能看起来像

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

void change(char (*a)[2][3]) {
*a[0][0] = 'k';
}

int main() {
char a[2][3];
char *tempWord = "sa";
strncpy(a[0], tempWord, strlen(tempWord));
strncpy(a[1], tempWord, strlen(tempWord));
change(&a);
}

除了 char(*a)[2][3] 之外还有其他指针定义吗? ?

我猜你确实想要一个 char ** ;您需要 mallocfree你对此的内存。类似的东西

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

void change(char **a) {
a[0][0]='k';
}

int main() {
char **a;
char *tempWord = "sa";
a = malloc(2 * sizeof(char **));
a[0] = malloc(strlen(tempWord) * sizeof(char *));
a[1] = malloc(strlen(tempWord) * sizeof(char *));
strncpy(a[0], tempWord, strlen(tempWord));
strncpy(a[1], tempWord, strlen(tempWord));
change(a);
printf("%s\n", a[0]);
free(a[1]);
free(a[0]);
free(a);
}

关于c - 如何为字符串数组创建指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55699073/

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