W nawiązaniu do wczorajszego wątku http://forum.pasja-informatyki.pl/206544/poprawne-obsluzenie-funkcji-strncpy zapytałem się o użycie funkcji strncpy(). Chyba jestem ślepy ponieważ w moim kodzie nie widzę problemu, a i tak wypisanie znaków nie działa poprawnie. Proszę zobaczyć poniżej.
#include <iostream>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::strlen;
using std::strncpy;
/*
* Class
*/
class Car {
private:
char * name;
size_t year;
public:
Car();
Car(char * carName, size_t carYear);
Car(Car & copy);
~Car();
friend ostream & operator<<(ostream & os, Car & object);
};
/*
* Constructors
*/
Car::Car() : year(2016) {
cout << "[default constructor]" << endl;
name = new char[4];
strncpy(name, "BMW", 3);
}
Car::Car(char * carName, size_t carYear) : year(carYear) {
cout << "[parameters constructor]" << endl;
size_t length = strlen(carName);
name = new char[length + 1];
strncpy(name, carName, length);
}
Car::Car(Car & copy) : year(copy.year) {
cout << "[copy constructor]" << endl;
size_t length = strlen(copy.name);
name = new char[length + 1];
strncpy(name, copy.name, length);
}
Car::~Car() {
cout << "[destructor]" << endl;
delete [] name;
}
/*
* Overloading operators
*/
ostream & operator<<(ostream & os, Car & object) {
os << "Name: " << object.name << endl;
os << "Year: " << object.year << endl;
return os;
}
/*
* Prints one char on each line
*/
void printCharArray(char * array)
{
size_t length = strlen(array);
for (size_t i = 0; i < length; ++i) {
cout << "(" << i << "): " << array[i] << endl;
}
}
/*
* Main function
*/
int main() {
Car firstCar;
Car secondCar("Mercedes", 2016);
cout << firstCar << endl;
cout << secondCar << endl;
cout << endl;
// test function on another array
char * array = new char[4];
strncpy(array, "ABC", 3);
printCharArray(array);
cin.get();
return 0;
}