[英]2-d Char array in C Unexpected output
I have this Piece of COde that store a string in a 2-d char array.IN my code i am using a 2x6 2-D char array.On providing a 12digit string LIKE > "COMEHOMEARUN". 我有这条代码,将一个字符串存储在一个2-d char数组中。在我的代码中,我正在使用2x6 2-D char数组。在提供12位字符串LIKE>“ COMEHOMEARUN”时。 It should store it as
它应该将其存储为
COMEHO COMEHO
MEARUN MEARUN
but I am getting the output as 但我得到的输出为
COMEHM COMEHM
MEARUN ...ie the value at [0]6] automatically gets the value of [1][0]. MEARUN ...即[0] 6]的值自动获得[1] [0]的值。
here's the code 这是代码
#include<stdio.h>
#include<conio.h>
void main()
{
char string[20];
char aray[1][5];
int i,j,k=0;
gets(string);
//storing the individual characters in the string in the form of 2x6 char array
for(i=0;i<=1;i++)
{
for(j=0;j<=5;j++)
{
aray[i][j]=string[k];
k++;
}
}
//displaying the array Generated
for(i=0;i<=1;i++)
{
for(j=0;j<=5;j++)
{
printf("%c ", aray[i][j]);
}
printf("\n");
}
getch();
}
Does anybody know where I am going wrong? 有人知道我要去哪里错吗?
In a C array declaration like char array[N][M]
, the N
and M
values are not "the highest valid index"; 在像
char array[N][M]
这样的C数组声明中, N
和M
值不是 “最高有效索引”; they mean "the number of values". 它们的意思是“值的数量”。
So your declaration 所以你的声明
char aray[1][5];
defines an array sized 1x5, not 2x6 as you intend. 定义一个大小为1x5的数组, 而不是您想要的2x6。
You need: 你需要:
char aray[2][6];
But of course, the actual indexing is 0-based so for char aray[2][6]
, the "last" element is at aray[1][5]
. 但是当然,实际的索引是基于0的,因此对于
char aray[2][6]
,“最后一个”元素位于aray[1][5]
。
您可以尝试将char aray[1][5]
更改为char aray[2][6]
Your indexing is not correct. 您的索引不正确。
When you declare any char array you have to give sufficient length. 声明任何char数组时,必须提供足够的长度。 In your code you give the dimension 1 but it required 2.
在您的代码中,给定维度1,但需要2。
Declare the array as: 将数组声明为:
char array[2][6];
That will work. 那可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.