Domanda

I have put a simplified version of my code here. What I'm trying to do is to read every line from an input file and store it in class "fifo". Before every store however, I try printing my previous fifo value (this was for debugging). What I see is that the previous value is being overwritten even before I call the fifo.add function. The getline function itself is overwriting the fifo on its own. Can somebody please tell me what is going on here?

//fifo.h

#ifndef FIFO_H_
#define FIFO_H_

class fifo {
        private:
                char* instr_arr;
                int head;
                int tail;
        public:
                fifo();
                fifo(int,int);
                void add(char*);
                void print_instruction(void);
};

#endif

//fifo.cpp

#include "fifo.h"
#include <iostream>
//using namespace std;

fifo::fifo() {
        head = 0;
        tail = 0;
        instr_arr = "NULL";
}

fifo::fifo(int h, int t) {
        head = h;
        tail = t;
}

void fifo::add (char *instr) {
        instr_arr = instr;
}

void fifo::print_instruction (void) {
        std::cout << instr_arr << std::endl;
}

//code.cpp

#include <iostream>
using namespace std;
#include <fstream>
using namespace std;
#include "fifo.h"

#define MAX_CHARS_INLINE 250

int main (int argc, char *argv[]) {
        char buf[MAX_CHARS_INLINE];     //Character buffer for storing line
        fifo instruction_fifo;          //FIFO which stores 5 most recent instructions

        const char *filename = argv[1];
        ifstream fin;
        fin.open(filename);

        while(!fin.eof()) {
                std::cout << buf << std::endl;
                fin.getline(buf, MAX_CHARS_INLINE);
                instruction_fifo.print_instruction();  //This instruction prints the line which was read from getline above!! Why??
                instruction_fifo.add(buf);
                }
        return 0;
}
È stato utile?

Soluzione

You are not actually storing the data in the FIFO (or in a memory block managed by the FIFO), only the pointer (which points to buf).

When you print instr_arr, you are basically printing buf, because instr_arr points to buf.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top