[英](C Programming) How do I insert string into a character array and then print out all the elements of this array?
我有这个以字符数组temp
形式显示的字符串。 我想把这个字符数组插入到另一个数组temp_list
,然后打印出这个数组的内容。 换句话说,将多个字符数组存储在一个数组中。 谁能告诉我这是否可行,我该如何使它起作用?
这是我试图完成的一个例子:
int main()
{
char temp[5] = "begin";
char temp_list [10];
temp_list[0] = temp;
for (int i = 0; i < strlen(temp_list); i++)
{
printf("Labels: %s,", temp_list[i]);
}
}
当我运行这个程序时,它打印出乱码。
任何形式的指导将不胜感激。 谢谢你。
编辑:
谢谢你的回答。 他们都非常有帮助。 但我还有另一个问题……如果我有多个字符数组要插入到temp_list
怎么temp_list
? 多次使用strcpy
似乎不起作用,因为我假设该函数基本上用strcpy
传递的字符串替换了temp_list
的全部内容?
关于字符串有很多误解。 您的数组temp
需要足够大以存储空终止符,因此在这种情况下它的大小至少需要6
:
char temp[6] = "begin"; // 5 chars plus the null terminator
要复制字符串,请使用strcpy
:
char temp_list[10];
strcpy(temp_list, temp);
要打印它,请传递temp_list
,而不是temp_list[i]
,您也不需要该循环:
printf("%s\n", temp_list);
最终的程序可能如下所示:
int main()
{
char temp[6] = "begin";
char temp_list[10];
strcpy(temp_list, temp);
printf("%s\n", temp_list);
return 0;
}
你在这里有三个问题。 首先, temp
不足以容纳字符串“begin”。 C 中的字符串是空终止的,所以这个字符串实际上占用了 6 个字节,而不是 5 个。所以让temp
足够大以容纳这个字符串:
char temp[6] = "begin";
或者更好:
char temp[] = "begin";
完全按照字符串的需要调整数组的大小。 第二个问题在这里:
temp_list[0] = temp;
您正在将一个数组(实际上是指向数组第一个元素的指针)分配给另一个数组的第一个元素。 这是分配的类型不匹配char *
的char
。 即使类型匹配,这也不是复制字符串的方式。 为此,请使用strcpy
函数:
strcpy(temp_list, temp);
最后,您没有正确打印结果:
for (int i = 0; i < strlen(temp_list); i++)
{
printf("Labels: %s,", temp_list[i]);
}
%s
格式说明符需要一个指向char
数组的指针以打印字符串,但您传入的是单个字符。 不匹配的格式说明符调用未定义的行为。
要打印单个字符,请改用%c
:
for (int i = 0; i < strlen(temp_list); i++)
{
printf("Labels: %c,", temp_list[i]);
}
或者您可以摆脱循环并使用%s
打印整个字符串:
printf("Labels: %s", temp_list);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.