2

I wish to define an array in a class, and set the variables of the class to the elements of the array. The implementation below results in segmentation fault:

class Grade {
    char MAP[];
    char *letter;
public:
    Grade();
    ~Grade();
    void set(int);
};
 Grade::Grade(){
    letter = new char;
    *letter = '\0';

    MAP[0] = 'A';
    MAP[1] = 'B';
    MAP[2] = 'C'; // result in segmentation fault

    MAP = { 'A', 'B', 'C'}; // result in segmentation fault
    }

Grade::~Grade(){
    delete letter;
    delete percent;
}

void Grade::set(int a){
    *letter = MAP[a];
}

How should I fix it?

3 Answers 3

3

Quickest way is to change char MAP[]; to char MAP[3];

There are other interesting things in the code.

1) It does not compile as given (you never define what a percent is).
2) What happens if someone sends an "int a" to your set function that is outside of the range of your map? (IE: 56 instead of 0, 1, or 2)?

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

Comments

2

Making some assumptions about what you intend the code to do, it appears that the easiest fix is to replace the current

char MAP[];
char *letter;

...

void Grade::set(int a){
    *letter = MAP[a];
}

with

char letter_;

...

void Grade::set( int const grade )
{
    // Assuming grade in range 1 through 5 inclusive.
    letter_ = "ABCDEF"[grade - 1];
}

By the way, it's a good idea to reserve ALL UPPERCASE identifiers for macros. That way you minimize the probability of unintended text substitutions. Also, it's easier on the eyes.

Comments

1

In case of Arrays the compiler requires you to explicitly declare the number of elements in your array. This is to ensure that the size of the array is determined before the execution.

Hence declaring an array as follows char MAP[]; will always result in a compilation error.

A probable solution for your problem will be to [as mentioned by David D] to declare it as char MAP[3];

But, in case your requirement is to have dynamic allocation you can declare it as

char *MAP;

and inside the constructor allocate the required memory as follows:

MAP = new char[ n ];

where n denotes the number of elements you require inside the array.

Note: If you declare the array dynamically you need to use

  delete[] MAP;

during destruction to complete free the memory.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.