Указатель в C ++ не инициализирован правильно

0

Я пытаюсь выполнить следующий код, все в порядке, кроме одного, и что tellerArray [2] никогда не инициализируется должным образом, он всегда создает проблемы для меня, и я не знаю почему. Это создает проблему для меня: я узнал об этом, когда несколько раз отлаживал код.

#include <iostream>
#include <stddef.h>

using namespace std;

class Customer {
public:
    void setTime(int time) { this->_time = time; }
    int getTime() { return this->_time; }
    void setNextCustomer(Customer *next) { this->_next = next; }
    Customer* getNextCustomer() { return this->_next;}
private:
    int _time;
    Customer *_next;
};


class Teller {
public:
    Teller();
    ~Teller();
    void addCustomer(Customer *customer);
    int totalCustomers();
    int totalTime();

private:
    Customer *head;
    Customer *tail;
};

Teller::Teller() {
    this->head = NULL;
    this->tail = NULL;
}

Teller::~Teller() {
    delete head;
    delete tail;
    head = NULL;
    tail = NULL;
}

void Teller::addCustomer(Customer *customer) {
    customer->setNextCustomer(NULL);
    if(head == NULL) {
        head = customer;
    } else {
        tail->setNextCustomer(customer);
    }
    tail = customer;
}

int Teller::totalTime() {
    int totalTime = 0;
    Customer *tempCust = new Customer;
    for(tempCust = head; tempCust != NULL; tempCust = tempCust->getNextCustomer()) {
        totalTime += tempCust->getTime();
    }
    return totalTime;
}

int Teller::totalCustomers() {
    int totalCustomers = 0;
    Customer *tempCust = new Customer;
    for(tempCust = head; tempCust != NULL; tempCust = tempCust->getNextCustomer()) {
        totalCustomers += 1;
    }
    return totalCustomers;
}


int getLeast(int, int, int, int);
int getMax(int, int, int, int);


int main(int argc, const char*argv[]) {


    Teller *tellerArray[4];

    // creating four tellers ( counters )
    Teller *tellerOne   = new Teller();
    Teller *tellerTwo   = new Teller();
    Teller *tellerThree = new Teller();
    Teller *tellerFour  = new Teller();

    tellerArray[0] = tellerOne;
    tellerArray[1] = tellerTwo;
    tellerArray[2] = tellerThree;
    tellerArray[3] = tellerFour;

    char wannaBuyAnother = 'n';
    int  duration = 0, minTime = 0, maxTime = 0, index = 0;

    do {
        cout<<"Enter duration of your transaction: ";
        cin>>duration;
        Customer *customer = new Customer;
        customer->setTime(duration);
        minTime = getLeast(     tellerOne->totalTime(),
                                tellerTwo->totalTime(),
                                tellerThree->totalTime(),
                                tellerFour->totalTime()     );

        for(index = 0; index < 4; index++) {
            if( (tellerArray[index]->totalTime()) == minTime ) {
                break;
            }
        }



        tellerArray[index]->addCustomer(customer);

        cout<<"You can stand in Queue "<<index + 1<<"\n";

        cout<<"Do you want to buy another Ticket(Y/N)? ";
        cin>>wannaBuyAnother;

    } while ( wannaBuyAnother == 'y' || wannaBuyAnother == 'Y' );


    cout<<"Number of Customers Deal By Every Teller\n";

    for(index = 0; index < 4; index++) {
        cout<<"T"<<index<< "= \t"<<tellerArray[index]->totalCustomers()<<"\n";
    }

    maxTime = getMax( tellerOne->totalTime(),
                            tellerTwo->totalTime(),
                            tellerThree->totalTime(),
                            tellerFour->totalTime()  );
    for(index = 0; index < 4; index++) {
        if( (tellerArray[index]->totalTime()) == maxTime ) {
            cout<<"TELLER "<<index+1<<" Deal Maximum Customers of the Day\n";
            break;
        }
    }

    return 0;
}





int getLeast(int first, int second, int third, int fourth) {
    int min = first;
    if( second < min ) {
        min = second;
    } else if ( third < min ) {
        min = third;
    } else if ( fourth < min ) {
        min = fourth;
    }
    return min;
}

int getMax(int first, int second, int third, int fourth) {
    int max = first;
    if( second > max ) {
        max = second;
    } else if ( third > max ) {
        max = third;
    } else if ( fourth > max ) {
        max = fourth;
    }
    return max;
}

Здесь выводится, когда я отлаживаю свой код.

tellerArray[0]  Teller *    0xbffff308  
tellerArray[1]  Teller *    0x8048c64   
tellerArray[2]  Teller *    0x1 
tellerArray[3]  Teller *    0xffff

Фактически мой код использует связанный список (класс клиента) для создания очереди (класс кэдера), а затем, основываясь на времени каждой очереди, он определяет, в какую очередь поставить следующего клиента?

Теги:
pointers

2 ответа

3
Лучший ответ

Инициализация выглядит отлично. Эти значения являются нечетными, но если у вас нет конкретной сборки отладки, вы не всегда можете полагаться на правильное значение указателя. Однако возможно, что они повреждены из-за следующего неопределенного поведения в вашей программе:

Я замечаю, что вы никогда не инициализируете указатель _next на Customer to NULL и не устанавливаете его, когда добавляете его в список. Таким образом, у вашего хвоста списка всегда есть неопределенный указатель _next. Это, скорее всего, даст вам проблемы.

Вы должны создать конструктор по умолчанию для Customer и инициализировать _next до NULL.

Одна несвязанная вещь, о которой я расскажу, это то, что ваши функции getLeast и getMax не работают. Почему бы вам не попробовать:

cout << getLeast(4, 3, 2, 1) << endl;
cout << getMax(1, 2, 3, 4) << endl;
  • 0
    Я удалил else из функций getLeast и getMax и они работают нормально. И я также создал конструктор, чтобы правильно инициализировать значение. Сейчас все хорошо.
2

Код немного странный, я не вижу, как код соответствует описанию того, что он должен делать.

Но ошибок не сложно найти, посмотрите на этот код

int Teller::totalTime() {
    int totalTime = 0;
    Customer *tempCust = new Customer;
    for(tempCust = head; tempCust != NULL; tempCust = tempCust->getNextCustomer()) {
        totalTime += tempCust->getTime();
    }
    return totalTime;
}

Ни в коем случае ваш код не установил значение для tempCust->_next поэтому tempCust->getNextCustomer() возвращает значение мусора, и поэтому с этого момента все ставки отключены, и ваш код может в итоге что-то сделать.

Честно говоря, я не вижу никакой логики для вашего кода, поэтому я не уверен, что делать, чтобы исправить это. По крайней мере, я бы посоветовал установить _next в NULL в конструкторе Customer.

class Customer {
public:
    Customer() { this->_next = NULL; }
    ...
private:
    ...
    Customer *_next;
};
  • 0
    Мой код устанавливает значение для tempCust->_next когда я Teller::addCustomer(Customer *customer) функцию Teller::addCustomer(Customer *customer) за исключением хвоста, когда я не устанавливаю значение tempCust->_next . Это была проблема. Я следовал твоей инструкции, чтобы создать конструктор .

Ещё вопросы

Сообщество Overcoder
Наверх
Меню