0

I'm using C++ and am trying to set an array element values with a setter method. The array is a class private member:

class Boo{
  private:
     int *x;
  public:
     Boo();
     ~Boo();

     void setX(int,int);
     int getX(int);
}

Boo::Boo(){

  x = new int[1];
  x = 0;
}

void Boo::setX(int value, int index){
      //set condition for NULL 
      x[index] = value;
}

int Boo::getX(int index){

    if(x[index] == NULL) {cout<<"invalid index"<<end; return;}
    return x[index];
}

void test(){
    Boo *p = new Boo();

    p->setX(12,0);
    cout<<p->getX(0)<<endl;
}

I been trying to test setting the values in 'x' starting with index '0' (like test()) but it crashes. I wanted to write a program where I run a loop counting up, and I set the array values. Can this be accomplish this way?

2
  • it crashes because x is set to null after you allocated it. stop by learncpp.com and see what they got to offer Commented Oct 7, 2016 at 3:41
  • I'm guessing the crash has something to do with the fact that you are setting the pointer x to 0 in your constructor, so then when you try to access the 0-th index in setX() you're trying to access an element that doesnt exist for x which gives you undefined behavior (or possibly a seg fault). Commented Oct 7, 2016 at 3:44

2 Answers 2

1

Do not use new in C++!

In this case, you should use std::vector<int>.


If you want to fix your code unless use std::vector,

#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <memory>
using std::size_t;

class Boo {
private:
    int *x;
    size_t size;
    size_t capacity;
public:
    Boo();
    ~Boo();
    void setX(int,size_t);
    int getX(size_t);
};
Boo::Boo() : size(), capacity(1) {
    this->x = new int[1];
    //x = 0;//DO NOT ASSIGN NULL POINTER!!!!
}
Boo::~Boo() noexcept {
    delete[] x;
}
void Boo::setX(int value, size_t index){
    if(this->capacity <= index) throw std::out_of_range("Boo::setX");//YOU MUST CHECK RANGE
    this->x[index] = value;
    ++this->size;
}

int Boo::getX(size_t index){
    if(this->size <= index) throw std::out_of_range("Boo::getX");//YOU MUST CHECK RANGE
    return x[index];
}

void test(){
    auto p = std::make_unique<Boo>();
    p->setX(12,0);
    std::cout << p->getX(0) << std::endl;
}
int main(){
    test();
}

http://melpon.org/wandbox/permlink/aIhwC5c9o1q8ygIo

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

Comments

0
Boo::Boo()
{
    x = new int[1];
    x = 0;
}

you are not able to set value in an array because after initializing with memory, you have set the pointer of an array to null in constructor.

please use x[0] = 0; instead of x = 0;

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.