我正在尝试将字符串值分配给C中的2d数组。到目前为止,我有以下代码,但它不起作用:
char array[9][6];
array[0][] = "[0x0a]";
array[1][] = "[0x09]";
array[2][] = "[0x0b]";
array[3][] = "[0x08]";
array[4][] = "[0x0d]";
array[5][] = "[0x0c]";
array[6][] = "[0x07]";
array[7][] = "[0x5c]";
array[8][] = "[0x22]";
我该怎么办? 感谢
答案 0 :(得分:4)
如果您不想静态分配它们,请使用strcpy()
功能:
#include <strings.h>
int main(int argc, char const* argv[])
{
char array[9][7];
strcpy(array[0], "[0x0a]");
strcpy(array[1], "[0x09]");
strcpy(array[2], "[0x0b]");
strcpy(array[3], "[0x08]");
strcpy(array[4], "[0x0d]");
strcpy(array[5], "[0x0c]");
strcpy(array[6], "[0x07]");
strcpy(array[7], "[0x5c]");
strcpy(array[8], "[0x22]");
return 0;
}
静态分配如下所示:
int main(int argc, char const* argv[])
{
char array[9][7] = {
"[0x0a]",
"[0x09]",
"[0x0b]",
"[0x08]",
"[0x0d]",
"[0x0c]",
"[0x07]",
"[0x5c]",
"[0x22]"
};
return 0;
}
(另外,数组的第二个维度应为7,而不是6。)
答案 1 :(得分:1)
有两种方法可以做到这一点。通过使用字符串文字进行静态初始化,如上所示:
代码清单
#include <stdio.h>
int main(void) {
int i;
char array[9][7] = {
"[0x0a]",
"[0x09]",
"[0x0b]",
"[0x08]",
"[0x0d]",
"[0x0c]",
"[0x07]",
"[0x5c]",
"[0x22]"
};
for (i=0; i<9; i++) {
printf("%d: %s\n", i, array[i]);
}
return 0;
}
或者,使用像这样的指针数组:
代码清单
#include <stdio.h>
int main(void) {
int i;
const char* array[9] = {
"[0x0a]",
"[0x09]",
"[0x0b]",
"[0x08]",
"[0x0d]",
"[0x0c]",
"[0x07]",
"[0x5c]",
"[0x22]"
};
for (i=0; i<9; i++) {
printf("%d: %s\n", i, array[i]);
}
return 0;
}
示例运行
0: [0x0a]
1: [0x09]
2: [0x0b]
3: [0x08]
4: [0x0d]
5: [0x0c]
6: [0x07]
7: [0x5c]
8: [0x22]
请注意,在第一个示例中,所有字符串都是相同的长度(您有一个错误,它们应该是7个字符长,以容纳终止C样式字符串的NULL / '\0'
)和所有字符串是读写的。在第二个例子中,字符串不需要是相同的长度,它们可以是不同的。它们也是只读的,就像以这种方式使用的任何字符串文字一样。
推荐阅读
<https://stackoverflow.com/questions/16021454/difference-between-declared-string-and-allocated-string>
答案 2 :(得分:1)
数组没有赋值运算符。在定义数组时设置值,例如:
char array[9][6] =
{
"[0x0a]", "[0x09]", "[0x0b]", "[0x08]", "[0x0d]",
"[0x0c]", "[0x07]", "[0x5c]", "[0x22]"
};
或者使用标准函数strcpy
:
char array[9][7];
strcpy( array[0], "[0x0a]" );
strcpy( array[1], "[0x09]" );
strcpy( array[2], "[0x0b]" );
strcpy( array[3], "[0x08]" );
strcpy( array[4], "[0x0d]" );
strcpy( array[5], "[0x0c]" );
strcpy( array[6], "[0x07]" );
strcpy( array[7], "[0x5c]" );
strcpy( array[8], "[0x22]" );
在最后一种情况下,数组元素的大小应等于7,包括终止零或大小可以等于6,但你必须使用函数strncpy
而不是{{1 }}
考虑到上面显示的数组的这种初始化仅在C中有效。在C ++中,你必须指定一个等于7的元素的大小,以包括字符串文字的终止零。