Reputation: 23
#include <iostream>
using namespace std;
struct Flight {
char flightNumber[6];
int depHour;
int depMin;
};
int main() {
char flightNumber[6];
int depHour;
int depMin;
cin.getline(flightNumber, 6);
cin >> depHour;
cin >> depMin;
Flight f = {.flightNumber = flightNumber[6], .depHour=depHour , .depMin= depMin};
cout << f.flightNumber << " " << f.depHour << " " << f.depMin << endl;
return 0;
}
Whatever I put in flightNumber doesn't show up. Compiles with no error but can't output flightNumber. It is empty. Any idea what the problem is?
Upvotes: 0
Views: 79
Reputation: 81926
.flightNumber = flightNumber[6]
That copies the character at index 6. Which is out of bounds on the array. And is therefore undefined behavior. This same bug also can cause you to print a string that is not null terminated, which also causes undefined behavior.
You need to use some form of strncpy()
That being said... I'm surprised this compiles with no warnings (and it does for me on clang).
#include <iostream>
using namespace std;
struct Flight {
char flightNumber[6];
int depHour;
int depMin;
};
int main() {
char flightNumber[6];
int depHour;
int depMin;
cin.getline(flightNumber, 6);
cin >> depHour;
cin >> depMin;
Flight f = {.depHour=depHour , .depMin= depMin};
strcpy(f.flightNumber, flightNumber);
cout << f.flightNumber << " " << f.depHour << " " << f.depMin << endl;
return 0;
}
#include <iostream>
using namespace std;
struct Flight {
Flight(char *flightNumber_, int depHour_, int depMin_): depHour(depHour_), depMin(depMin_) {
strcpy(flightNumber, flightNumber_);
}
char flightNumber[6];
int depHour;
int depMin;
};
int main() {
char flightNumber[6];
int depHour;
int depMin;
cin.getline(flightNumber, 6);
cin >> depHour;
cin >> depMin;
Flight f(flightNumber, depHour, depMin);
cout << f.flightNumber << " " << f.depHour << " " << f.depMin << endl;
return 0;
}
strcpy()
like I did. Use strncpy()
along with validation code to make sure you don't copy beyond the length of the allocated array.std::string
is a lovely type in c++.Upvotes: 3