Reputation: 3
I was just wondering. Say you will need to store these values:
Hours Minutes
inside an array, is the following implementation logically possible?
struct node
{
int hour;
int minutes;
};
int main()
{
int numOfLanding, minGap, hour, minutes;
cin>>numOfLanding;
cin>>minGap;
cout<<endl;
struct node *arr[numOfLanding];
for (int i=0; i<numOfLanding; i++)
{
cin>>hour;
cin>>minutes;
arr[i]->hour=hour;
arr[i]->minutes=minutes;
}
I am still trying very hard to understand struct node logic. Any help would be much appreciated!
Upvotes: 0
Views: 1789
Reputation: 5706
What you are asking is: is it possible to make an array of a size that is not known at compile time, but only at runtime? Yes, you can, but the way you have chosen is not standard C++: declaring an array like
struct node *arr[numOfLanding];
means using a "variable-length array", which is not (and has never been) part of the C++ standard. It was part of C, however, in C99, but then the committee decided to make it optional in C11. It is anyway possible to find a C++ compiler that supports this feature as an extension: gcc, for example. But if you use it, keep in mind that your code is not portable.
The standard way of doing it in C++ is to use new[]
:
node* arr = new node[numOfLanding];
(note that using the keyword struct
every time is what you would do in C; in C++ it is not required)
At this point, you access each element using the .
, not the ->
:
arr[i].hour=hour;
arr[i].minutes=minutes;
After you are finished using the array you have to delete it, by using:
delete[] arr;
Anyway, this style is old, and nowadays considered bad. The preferred approach is to use a container that automatically deals with the size for you, and that will manage memory so that you don't need to worry about new[]
and delete[]
. The best container for this is the std::vector. To use it, first you have to #include <vector>
, and then you can use it like this:
std::vector<node> arr(numOfLanding);
for (auto& curr_node : arr) {
cin>>hour;
cin>>minutes;
curr_node.hour=hour;
curr_node.minutes=minutes;
}
Upvotes: 3
Reputation: 57698
Yes, you can have an array of nodes.
However, if you insist on an array, and you don't know the capacity at compile time, you'll have to allocate it at run-time:
struct node
{
int hour;
int minutes;
};
int main()
{
int numOfLanding, minGap, hour, minutes;
cin>>numOfLanding;
cin>>minGap;
cout<<endl;
node *arr = new node[numOfLanding];
for (int i=0; i<numOfLanding; i++)
{
cin>>hour;
cin>>minutes;
arr[i].hour=hour;
arr[i].minutes=minutes;
}
// Remember to delete the array.
delete[] arr;
return EXIT_SUCCESS;
}
A safer alternative is to use std::vector<node>
.
Note: Since it is an array, use the '.' for access, not ->
.
Upvotes: 1