How to create Character based arrays in Turbo C++? - 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 :
Can anyone tell me where 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 <=.

Related

Which is correct for sizing a vector

Hi I am just starting to learn cpp and I have two examples of getting the size of a vector in the for statements both seem to work but which is right and why? sizeof(vector) or vector.size()?
Thanks
Brian
void print_vector(vector<string> vector_to_print){
cout << "\nCars vector = ";
for(int i = 0; i < sizeof(vector_to_print); i++){
cout << vector_to_print[i];
(i < vector_to_print.size()-1) ? (cout << ", ") : (cout << endl); // ? the tenrary operator is an if statement (?) do one outcome (:) or the other
}
}
void print_vector(vector <string> vector_to_print){
cout << "\nVector contents = ";
for( int i = 0; i < (vector_to_print.size()); i++ ){
cout << vector_to_print[i];
(i < (vector_to_print.size()-1)) ? (cout << ", ") : (cout << endl);
}
}
Both seem to work I try to rewrite the same code from memory each day for a week to help me learn it and I couldn't quite get the sizeof() to work so I googled it and the example I found used .size() but when I got home and checked what I did yesterday I had used sizeof().
std::vector<std::string> is a container class, which stores an array of std::strings plus other values to assist with manipulation of the array and providing information about the state of the stored array. When you call sizeof(vector_to_print) you are simply getting the size of the container class not the amount of elements in the array that it is storing.
run the following code to prove it to yourself:
std::vector<std::string> vec{"hello","world"};
std::cout << sizeof(vec) << '\n';
vec.push_back("!");
std::cout << sizeof(vec);
the size of the underlying array is changing it goes from 2 elements to 3, but not only does the sizeof(vec) not change, it is always = to 24!
sizeof(vec) must be the same each time (24 bytes on my machine) because sizeof is a compile time constant, because the size of a type must be a compile time constant.
The latter (.size()) is the only valid method
As you already know there are classes in C++. One class can have many methods doing different things and many fields holding different things. When we create an object of class Vector this object has method .size() which as mentioned here returns the number of elements in our object. The complexity is Constant and there is no problem using .size().
When you are using sizeof() as mentioned here on our object you know the size of the object with all its fields (for example vector can have size_t field where it counts all the elements and some field which holds them) you don't need the actual size of the vector in order to iterate the elements this could be wrong in many cases.
P.S. You must use .size()!

How to use the strlen() with 2d array?

I want to know the horizontal size of my 2D char array. I found strlen() for that, but it works only with a simple char array. With 2D it doesn't work. Any idea? Thanks for the answers!
char m[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
m[i][j] = ' ';
}
}
cout << "CHAR Matrix: " << endl;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
cout << "[" << m[i][j] << "]";
}
cout << endl;
}
cout << "Sizeof matrix -> " << sizeof(m) << "B" << endl;
cout << "Length of Matrix strlen(m[0]): " << strlen(m[0]) << endl;
The problem is that ,,strlen(m[0]),, gives me 18. How could i get 4?
You have a few things going on. Some of the comments above help, but let's go over it.
First, if you're using C++ and you're holding strings, you should use std::string. However, your problem indicates you're just learning, so let's stick to old-school C.
What you have allocated is a 2-dimensional array of single characters. That is, you are storing in total 12 characters of data.
In C (or C++) strings are null-terminated. That is, if you store as a string "Hi", it's actually 3 characters, not two. H, I, and a zero byte that indicates the end of the string.
strlen simply counts the number of characters until the zero byte. So in my example, 2.
You don't have any 0-bytes in your array, so strlen counts until it hits a zero due to some other reason -- completely outside your array. Yikes!
So... It's a mistake to use the string methods (strlen, strdup, etc) when dealing with single characters.
Now, the safest thing would be to use a vector of std::string, as others have suggested. However, I am a firm believer in understanding the basics before taking shortcuts, and that's a shortcut.
So if what you really want is 3 strings, but you want to use old-school C, then you should actually have a 1-dimensional array of char *.
char *m[3];
m[0] = "Hello";
m[1] = "there";
m[2] = "everyone";
It would be REALLY weird to store strings the way you have, and it's considered quite dangerous to use fixed-length character buffers for holding strings. This is where the infamous buffer overrun exploits come from, the most common exploits in old school web applications.
Alternatively, you could modify your example. make m[3][5], and store a zero-byte in each row after the end of your strings. strlen() will start to work. But it's really kind of ugly.

Program not running with Array during Initialization

I'm just practicing using arrays. So my program consist of inputting numbers of data type double into the array and have them print out. Simple.
I only limited the numbers down to 4. So the array, num_List[3] is in the code. I've made sure to use the for loops properly for reading and printing out the result.
The first few times I tested the code. I realized that the 4th number in the array was in scientific notation, telling me that I forgot to initialize the array to 0, in this case 0.0, since I'm using double. So I put in this code.
for (index = 0; index <= 3; index++)
num_List[index] = 0.0;
This code should have initialized the arrays of num_List to 0.0. However, when I tested this, nothing came up, after I inputted the 4 numbers. So I made a logical error here or it's something else with the for loop that's causing it to be trapped and not continue the execution.
I've read in the books about this particular way to initialize.
#include <iostream>
using namespace std;
int main() {
double num_List[3]; // These are my variables
int index;
//double num; // Ignore these two for now, for they are to be modified later on.
//double result;
cout << "This program will summarize the numbers you've inputted print out the result. \n";
cout << "And also print out the address of the 1st and 4th address in the array." << endl;
cout << "Please enter the four numbers to be summarized.";
for (index = 0; index <= 3; index++) { // I put this in after I realized my mistake of not initializing my arrays to 0.0.
num_List[index] = 0.0;} // This is where the problem is, I think.
for (index = 0; index <= 3; index++) // This reads in the user the input
cin >> num_List[index];
cout << "The numbers you have inputted is:\n";
for (index = 0; index <= 3; index++) // This prints out the array.
cout << num_List[index] << ", " << endl;
return 0;
}
If you focus on the aforementioned code, and try to compile it, you'll see that my code unfortunately doesn't continue on from there after you input 4 numbers, regardless of whether or type a number and space it up to 4 numbers, or input a number, press the enter key for those numbers. Most likely I've made a obvious mistake, but I'm having some trouble seeing it.
I use Code Blocks, so things are a little different compared to the Bloodshed C++ compiler I used to use to practice codes on.
double num_List[3];
This declares an array with 3 elements, indexed 0 through 2.
for (index = 0; index <= 3; index++)
This loops through 4 indices, 0 through 3. When you do something with num_List[3], you get undefined behavior. In your trial, the undefined behavior fortunately resulted in just some garbage output.

Array with loop

I just started to learn programming 2 months ago and I am still newbie in it. I just learn how to write a code of arrays with loop. This was my code.
#include <iostream>
using namespace std;
int main()
{
int array[5];
for(int x=1; x<=5; x++)
{
fidan[x]=16;
cout<<x<< " --- " << array[x]<<endl;
}
return 0;
}
I know that array is count from 0. But I want my program to start with 1. So, at for loop instead of x=0, I write x=1. Then at my last x it started to being weird.
Can someone help me with it. I would appreciate it. Thank you
array[5] means an array with 5 elements. These elements are:
array[0],array[1],array[2],array[3],array[4].
Now you can declare it as array[6] and then you will have an array[5] element. Now your code should have produced a segmentation fault when accessing the array[5] element, but this is undefined behavior so who knows to whom that memory segment belongs to.
The weird characters that you get is because that memory does not belong to the array variable and probably cannot be interpreted as int. Hope that helps.
you should use one of two ways:
for (int i = 0 ; i < 5 ; i++)
cout << array[i] << " ";
or
for (int i = 1 ; i <= 5 ; i++)
cout << array[i - 1] << " ";
Your array is with 5 elements.
When x=5 in the loop, you are accessing the 6th element, so you are out of the bounds of the array.
I know that array is count from 0.
Correct.
But I want my program to start with 1.
Well, it doesn't. As you just said.
So, at for loop instead of x=0, I write x=1.
Simply don't do that.
Then at my last x it started to being weird.
Yes, because you tried to access an array element that doesn't exist.

Absence of loop is rendering code useless?

First of all, this is NOT homework. I'm using a book I bought for myself to learn the beginning of C++ at home, and it contains an exercise I'm stuck with. It asks me what is wrong with the following code, but I can't seem to find it. First I thought that it had to do with the fact that there wasn't a while or for loop and thus it couldn't repeat itself rendering the 'i' useless, but I'm not sure if that's the true issue here.
for (int i = 0; i <= phrase.size(); ++i)
{
cout << "Character at position " << i << " is: " << phrase[i] << endl;
}
The condition is wrong: i <= phrase.size() should be i < phrase.size(). Say phrase is a vector of 10 elements. size() will return 10, but in last iteration of the loop, phrase[10] is accessing an element which isn't there. Dereferencing out of bounds is undefined behaviour, which by C++ standard makes the whole program ill-formed.
i < phrase.size() // Given that you are starting from 0th index, I assume
// that the valid array indexes are 0 to N-1
I suspect it is the <= size() that is the problem, on the last loop the phrase[i] will actually be one past the end of the array causing a bad reference, so should be:
for (int i = 0; i < phrase.size(); ++i)
{
cout << "Character at position " << i << " is: " << phrase[i] << endl;
}
The problem is on this line:
for (int i = 0; i <= phrase.size(); ++i)
The value of i will get at one point equal to phrase.size(), which, when indexed later by phrase[i] is out of bounds, as indixing in C++ is zero-based.
It's mostly a good guideline to always include the start bound and exclude the last.
So write:
for (int i = 0; i < phrase.size(); i++)
That way i starts with 0 and ends with the last item.
<= phrase.size() should be < phrase.size(). The last iteration of the loop will have an i equal to phraze.size() which is out of bounds since whatever you're iterating starts with an index of 0.
Imagine you have 10 items, but counting numbers for them will be look like 0, 1 .., 8, 9. So you should check it by "strictly less" operator. This fact is confusing first time, but then you will see how is it comfortable.