我在这里放了一个简化版的代码。我要做的是从输入文件中读取每一行并将其存储在“fifo”类中。然而,在每个商店之前,我尝试打印我之前的fifo值(这是用于调试)。我看到的是,即使在调用fifo.add函数之前,前一个值也被覆盖了。 getline函数本身会自行覆盖fifo。有人可以告诉我这里发生了什么吗?
//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;
}
答案 0 :(得分:1)
您实际上并未将数据存储在FIFO(或由FIFO管理的存储器块中)中,而只存储指针(指向buf
)。
当您打印instr_arr
时,基本上是打印buf
,因为instr_arr
指向buf
。