开发者

How to create Character based arrays in Turbo C++?

I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :

char x[7][7] = {"sec","min","hr","day","week","month","year"};

And when I try to fetch the data from it like this :

for (i=0;i<=7;i++){
  cout << x[i] << "\n";    
} 

I get some strange results! Like this :

How to create Character based arrays in Turbo C++?

Can anyone tell me wh开发者_JS百科ere I'm going totally wrong! And please I'm new to C++ so can you provide me a good explanation.


Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify your for loop as for (i=0;i < 7;i++). (< instead of <=.)

You're going over the end of the array, which may give you garbage data or may just crash your program.


for (i=0;i<=7;i++){
  cout << x[i] << "\n";    
}

The array indices will only range from 0 to 6, and you check for i<=7. Change that to i < 7.


The problem is not in creating the array but in printing the results. Arrays in C, C++, Java, C#... and many other languages are 0 based. When you declare an array of 7 elements you iterate from 0 to 6:

for ( int i = 0; i < 7; ++i ) {
   std::cout << x[i] << std::endl;
}

Note: < and not a <=.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜