0

I'm having a little bit of trouble printing out a member of my struct. This is what I have so far:

struct Code
{
  char letter;
  string sequence;
}

void createCode(HuffmanNode *root, string codestr, Code *codeBook, int count)
{
  if(root->getRight() == NULL && root->getLeft() == NULL)
  {
    Code code;
    code.letter = root->getLetter();
    code.sequence = codestr;
    codeBook[count] = code;
    count++;
  }
  else
  {
    createCode(root->getLeft(), codestr + "1", codeBook, count);
    createCode(root->getRight(), codestr + "0", codeBook, count);
  }
}

This works all fine, but in main when I try to print out the member sequence in my array of Codes in Codebook:

string codestr;
count = 0;
Code codeBook[256];
createCode(root, string codestr, codeBook, count); //root is already created 
for(int i = 256; i >= 0; i--)
{
  if(isalpha(codeBook[i].letter))
  cout << codeBook[i].sequence << " ";
}

Only the last string I stored is printed. Might anyone know a fix and why this is happening? If anyone could help, that'd be great!

2 Answers 2

1

The main problem is that createCode() is always passed count=0. Because of this, you store all Code entries at the zeroth position in your array, and the last one overwrites all previous entries.

To fix, either pass count by reference or pointer, or make the function return the new value of count.

Finally, the starting value of the for loop is out of bounds (off by one).

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

3 Comments

Well when I call createCode() count is incremented in my if statement isnt it?
@user200081: Not really. You increment it in the first branch, and recursively call createCreate() in the second. You never do both.
Ah that helped. Thank you! I understand what I did wrong now. I need to pass by reference...
0

When you createCode, count is not incrementing, because you are passing it by value, change to pass by reference:

void createCode(HuffmanNode *root, string codestr, Code *codeBook, int& count)

array codeBook contains 256 elements but index is from 0 to 255. for loop should be:

for(int i = 255; i >= 0; i--)

Otherwise access out-of-boundry array element is undefined behavior.

2 Comments

Thanks for catching that! I just fixed that but it still didn't print out correctly... any other tips?
you shall pass count to createCode by reference

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.