如何在C中将字符串添加到2D数组 [英] How to add a string to a 2D array in C
问题描述
我开始学习C,并且遇到了将字符串输入添加到2D数组的问题,我能够正确获取字符串输入,但是当我尝试将字符串元素添加到数组时,它不是按预期工作。打印数组时(这是我测试程序的方式),它将为数组中的每个索引分配单个字符而不是整个字符串。
i am starting to learn C and I have ran into the problem of adding a string input to a 2D array, i am able to get the string input correctly but when i try and add the string element to the array it is not working as expected.When printing the array(which is how i test the program) it will assign each index in the array a single character instead of the entire string.
这是我查看的代码,在此先感谢您,感谢您发布的任何帮助。
And here is my code for viewing, thank you very much in advance i appreciate any help that is posted.
#include <stdio.h>
main()
{
char c_array[3][3];
int x;
int y;
int z=10;
int i_user_input;
char c_name[256];
for(x=0;x<=+2;x++)
{
for(y=0;y<=2;y++)
{
printf("\nPlease enter a name to the system:");
scanf(" %s",&c_array[x][y]);
printf("The string is %s\n",c_name);
printf("Please press '1' if you would like to keep entering names\n");
printf("Please press '2' if you would like to print the list of names:");
scanf("%d",&i_user_input);
if(i_user_input==1)
continue;
if(i_user_input==2)
for(x=0;x<=2;x++)
{
for(y=0;y<=2;y++)
{
printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
}
}
}
}
}
输出看起来像带有示例输入 Penelope!的
The output looks as follows with the sample input 'Penelope!'
c_array[0][0]=P
c_array[0][1]=e
c_array[0][2]=n
c_array[1][0]=e
c_array[1][1]=l
c_array[1][2]=o
c_array[2][0]=p
c_array[2][1]=e
c_array[2][2]=!
推荐答案
声明时:
char c_array [3] [3];
这意味着2D数组的每个元素都是一个字符(单个字符);
This means that each element of your 2D array is a "char" (a single character); not a "string of characters".
要使每个元素都是字符串,则需要以以下方式声明数组:
char string_array [3] [3] [256];
To have each element be a string of characters, you need to declare your array in the following way: char string_array[3][3][256];
我不确定这是您要执行的操作。 Mw的感觉是,您想要3个元素组成的数组,其中每个元素都是一个字符串。在这种情况下,[3]不够用,您的字符串必须少于两个字符(第三个字符保留为结尾的零)。
I am not sure this is what you want to do though. Mw feeling is that you want an array of 3 elements where each element is a string. In that case, [3] is hardly enough, your strings will have to be less than two characters (the third being reserved for the terminating zero).
这篇关于如何在C中将字符串添加到2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!