1,105,585 Community Members

Problem with 2-d Character Array

Member Avatar
anu07
Junior Poster in Training
66 posts since Jun 2010
Reputation Points: -3 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

The output I expected was:

alpha
beta

I used the following code:

#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    char choice[2][5]={"alpha","beta"};
    cout<<choice[0]<<endl;
    cout<<choice[1];
    getch();
}

But this is what comes:

alphabeta
beta

Can anyone tell me what I did wrong? Thank you.

P.S.:I know I am not using standard c++, but this is how we have to do in school.

Member Avatar
sarathsp06
Newbie Poster
1 post since Oct 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

Ts becouse alpha jst fills all the space allocatd and the next space will be filld with beta whch z not 5lettered and the string end"\0"is not present for alpha here ny way

Member Avatar
anu07
Junior Poster in Training
66 posts since Jun 2010
Reputation Points: -3 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

Ts becouse alpha jst fills all the space allocatd and the next space will be filld with beta whch z not 5lettered and the string end"\0"is not present for alpha here ny way

Can you elaborate, and with proper English? Thank you.

Member Avatar
Caligulaminus
Junior Poster
106 posts since Feb 2011
Reputation Points: 35 [?]
Q&As Helped to Solve: 30 [?]
Skill Endorsements: 0 [?]
 
0
 

There is not enough room in your array to hold "alpha". The C-string "alpha" ends with an additional '\0'(NUL)-character and thus needs 6 chars in the array. char choice[2][6]={"alpha","beta"}; should work.

Member Avatar
anu07
Junior Poster in Training
66 posts since Jun 2010
Reputation Points: -3 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

There is not enough room in your array to hold "alpha". The C-string "alpha" ends with an additional '\0'(NUL)-character and thus needs 6 chars in the array. char choice[2][6]={"alpha","beta"}; should work.

Thanks a lot Caligulaminus, it worked. I thought that, since "alpha" is held from choice[0][0] to choice[0][4], choice[0][5] should hold the null character.

Thanks again. :)

Question Answered as of 2 Years Ago by Caligulaminus and sarathsp06
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: