[英]How can I create a pointer for an array of strings?
I am new to C and not sure how to pass pointers/addresses properly when it comes to chars/strings. 我是C语言的新手,不确定在使用字符/字符串时如何正确传递指针/地址。 I can't get my head around these "strings", about how to master the pointers.
我对这些“字符串”一无所知,无法掌握指针。
I basically want to pass the address of the array "a" defined below to an arbitrary function, but I don't know how to define the pointer for this array. 我基本上想将下面定义的数组“ a”的地址传递给任意函数,但是我不知道如何为该数组定义指针。
Please help me! 请帮我!
I have the following code: 我有以下代码:
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);
}
You have a char[2][3]
so you can pass a char (*)[2][3]
to your change
function. 您有一个
char[2][3]
因此可以将一个char (*)[2][3]
传递给您的change
函数。 To copy tempWord
into your char[][]
you can use strncpy
. 要将
tempWord
复制到char[][]
,可以使用strncpy
。 Assuming I understand what you're trying to do, that might look like 假设我了解您要执行的操作,则可能看起来像
#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);
}
Is there any other definition of pointer other than char(*a)[2][3]
? 除
char(*a)[2][3]
之外,还有指针的其他定义吗?
I guess you really did want a char **
; 我想你确实想要一个
char **
; you will need to malloc
and free
your memory for that. 您将需要
malloc
并为此free
内存。 Something like 就像是
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.