Reputation: 179
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". It should store it as
C O M E H O
M E A R U N
but I am getting the output as
C O M E H M
M E A R U N ...i.e the value at [0]6] automatically gets the value of [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?
Upvotes: 2
Views: 265
Reputation: 1206
Your indexing is not correct.
When you declare any char array you have to give sufficient length. In your code you give the dimension 1 but it required 2.
Declare the array as:
char array[2][6];
That will work.
Upvotes: 0
Reputation: 399881
In a C array declaration like char array[N][M]
, the N
and M
values are not "the highest valid index"; they mean "the number of values".
So your declaration
char aray[1][5];
defines an array sized 1x5, not 2x6 as you intend.
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]
.
Upvotes: 4
Reputation: 172468
You can try by changing char aray[1][5]
to char aray[2][6]
Upvotes: 0