简体   繁体   中英

Create Dynamically Allocated Array of Pointers C++

I'm currently trying to dynamically allocate an array of character arrays and set values from another array of character arrays to the new dynamically array. When I print the values from the dynamically array I got some junk values and I can not understand where they come from.

Class -

class Class {

private:
    char** courses;
    int numberOfCourses;


public:
    Class();
    Class(const char** courses, int numberOfCourses);
    ~Class();

char** getCoursesList();
int getNumberOfCourses();


};

Constructor (allocate memory) -

Class:: Class(const char **courses, int numberOfCourses) {

if (numberOfCourses <= 0){
    this->numberOfCourses = 0;
    this->courses = nullptr;
} else{
    this->numberOfCourses = numberOfCourses;
    this->courses = new char*[numberOfCourses];
    for (int i = 0; i < numberOfCourses; i++) {
        cout << strlen(courses[i]) << endl; // 5
        this->courses[i] = new char[strlen(courses[i])];
        cout << strlen(this->courses[i]) << endl; // 22
        strncpy(this->courses[i], courses[i], strlen(courses[i]));

        }
    }
}

getNumberOfCourses -

int Class::getNumberOfCourses() {
    return this->numberOfCourses;
}

getCoursesList -

char **Class::getCoursesList() {
    return this->courses;
}

Main -

const char *courses[] = {"test1", "test2", "test3" };
Class d1(courses,3);

for (int i = 0; i < d1.getNumberOfCourses(); i++) {
    cout << d1.getCoursesList()[i] << endl;
}

Output -

[test1═²²²²▌▌▌▌▌▌l┴╓K▌] [test2═²²²²▌▌▌▌▌▌@┴2K▌] [test3═²²²²▌▌▌▌▌▌Y┴;K▌]

I would love to understand what I am doing wrong.

Look here as you may understand from the documentation, strlen function does not count \0 character which is end of the string. Hence it is not copied with strcpy function call, and cout does not encounter with \0 . This is the reason of absurd characters in terminal output. While allocating memory for course names, allocate for one more char and add \0 end of the char array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM