[英]How to declare and initialize an array of pointers to array of pointers to char?
I want to declare an array of pointers to array of pointers to char and initialize it.我想声明一个指向char指针数组的指针数组并初始化它。 But i couldn't declare and initialize it using the following way:
但我无法使用以下方式声明和初始化它:
char *(*array[])[] = {
{ "car", "toy", "game" },
{ "go", "play", "read" }
};
Please write the correct form of my declaration and initialization?请写出我的声明和初始化的正确形式? I get warning messages like "warning: brace around scalar initializer" and also "note: (near initialization for 'array[0]' )"
我收到警告消息,例如“警告:标量初始值设定项周围的括号”以及“注意:(接近 'array[0]' 的初始化)”
Before C99, you had to define the inner arrays separately:在 C99 之前,您必须单独定义内部数组:
#include <stdio.h>
int main() {
const char *array_0[] = { "car", "toy", "game" };
const char *array_1[] = { "go", "play", "read" };
const char **array[] = { array_0, array_1 };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%s ", array[i][j]);
}
printf("\n");
}
return 0;
}
With C99, you can now define and initialize the same object directly:使用 C99,您现在可以直接定义和初始化相同的对象:
#include <stdio.h>
int main() {
const char **array[] = {
(const char *[]){ "car", "toy", "game" },
(const char *[]){ "go", "play", "read" },
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%s ", array[i][j]);
}
printf("\n");
}
return 0;
}
Of course this is more flexible than a 2D matrix: each inner array can have a different size, as in:当然,这比二维矩阵更灵活:每个内部数组可以有不同的大小,如下所示:
#include <stdio.h>
int main() {
const char **array[] = {
(const char *[]){ "car", "toy", "game", NULL },
(const char *[]){ "go", "play", NULL },
(const char *[]){ "read", NULL },
NULL,
};
for (int i = 0; array[i]; i++) {
for (int j = 0; array[i][j]; j++) {
printf("%s ", array[i][j]);
}
printf("\n");
}
return 0;
}
Output:输出:
car toy game go play read
Note that I added the const
keyword because string literals should not be modified, so pointers to them should be defined as const char *
.请注意,我添加了
const
关键字,因为不应修改字符串文字,因此应将指向它们的指针定义为const char *
。
char *(*array[])[] = {
&(char*[]){"car","toy","game" },
&(char*[]){"go","play","read" }
};
compiles without a warning.编译时没有警告。
It's not nested arrays, it's an array of pointers ( &
) to arrays of char*
(char*[]`) so I don't think you can do without either compound literals or separate array objects to make array pointers out of.它不是嵌套数组,它是一个指向
char*
(char*[]`) 数组的指针 ( &
) 数组,所以我认为如果没有复合文字或单独的数组对象来制作数组指针,您就无法做到。
(Don't forget that assigning to char*
from string literals is kind of a bad practice as string literals are practically, though not formally (不要忘记从字符串文字中分配给
char*
是一种不好的做法,因为字符串文字实际上是,尽管不是正式的char const[]
, so using
char const* instead of
char *` would be preferable.) char const[]
, so using
char const* instead of
char *` 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.