My assignment is to mimic the Unix tail command. For those of you who do not know it, it prints out the last n lines of a file. I think I am going to have a lot of questions.
We can't use
std::vector<std::strings>
, we must use
char**
So the char** is allocated to hold n lines, and then each char* in the array is allocated to hold the line. We make this buffer circular, and end up with the three variables:
1 2 3
|
char** lines;
char** current;
char** end;
|
current is used to iterate through the lines, and end is to know when the end of the array is found so that current will go back to the start (lines).
I've got a problem right off the bat...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
int createLines(unsigned int amount)
{
/* General Safety */
if (lines != NULL) return -1;
amount = (amount < MAX_LINES? amount: MAX_LINES);
/* Create Lines */
lines = new char*[amount];
/* Define important positions*/
current = lines;
end = lines + (sizeof(char*) * (amount - 1));
std::cout << lines << " " << current << " " << end << std::endl;
/* Set array to NULL*/
int i;
for (i = 0; i < amount; i++)
{
std::cout << &lines[i] << std::endl;
lines[i] = NULL;
}
return 0;
}
|
When this function is given an amount of 2, I get the output
00345B88 00345B88 00345B98
00345B88
00345B8C |
I think the value of 'end' isn't correct. Shouldn't it be 00345B8C?
Edit: changing line 12 to be
sizeof(char)
gives me the right number? I must be thinking about memory wrong.