0

I am trying to pass a character array to a function. Set the values onto a character array. Then retrieve it and print using another function. But not able to get the result. Here is the code

class cSummary{
    private:
       char *cSummaryTable[2];
    public:
       void printSummary();
       void setSummary(char *ptr, int stage);
       char *getSummary();
};
void cSummary::printSummary(){
    char *cPtr = getSummary();
    for(int i = 0; i < 2; i++){
        cout << cPtr[i] << endl;
    }
}
void cSummary::setSummary(char ptr[], int stage){
    switch(stage){
        case 0: 
            cSummaryTable[0] = ptr; 
            break;  
        case 1:
            cSummaryTable[1] = ptr;
            break;
    }
}
char *cSummary::getSummary(){
    return *cSummaryTable;
}
int main(int argc, char const *argv[])
{
    cSummary summary;

    summary.setSummary("first message!",   0);
    summary.setSummary("second message!!", 1);

    summary.printSummary();

    return 0;
}
1
  • 5
    First, this looks more like C than C++. In C++ you can just use a vector of strings. Second, passing string literals to a function should be as const char*. Third, your error is returning *cSummaryTable in getSummary() when you should be returning simply the cSummaryTable Commented Dec 22, 2018 at 8:16

1 Answer 1

1

getSummary is the problem since it only returns the first string. Notice the assymmetry between getSummary and setSummary, setSummary has a stage parameter but there's no such parameter in getSummary. That should have been a clue that something was wrong. I would recode like this

char *cSummary::getSummary(int stage) {
    return cSummaryTable[stage];
}

void cSummary::printSummary() {
    for(int i = 0; i < 2; i++){
        cout << getSummary(i) << endl;
    }
}

And I'll add the obiligatory piece of good advice. You should learn to program modern C++, which doesn't use arrays and pointers, but uses the much safer and easier to understand std::string and std::vector instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.