2

This is my program. The output should be a sequence of 'a' chars, but for some reason it's not. Why?

#include <iostream>

using namespace std;

const int NAME_LENGTH = 16;

struct Record {
    char hotel_name[NAME_LENGTH];
};

int main() {
    int amount = 5;
    for (int i = 0; i < amount; i++) {
        Record * elementToBeAdded = new Record;
        for (int j = 0; j < NAME_LENGTH; j++)     
            elementToBeAdded->hotel_name[i] = 'a';
        elementToBeAdded->hotel_name[NAME_LENGTH-1] = '\0';
        cout << "string-" << elementToBeAdded->hotel_name << "-\n\n";
    }
}
1
  • +1 for including a short, complete testcase. See sscce.org Commented Mar 29, 2012 at 20:15

6 Answers 6

6

Because you have a typo in

        elementToBeAdded->hotel_name[i] = 'a';

You mean j, not i.

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

Comments

2

Your innermost loop is using i when it surely intends to use j:

elementToBeAdded->hotel_name[i] = 'a';

as a result, you'll never set the zeroth element of Record #1's char[], nor the one-th element of Record #2's, etc. That means that every time through the outermost loop except the first, the very first char in the hotel name will remain uninitialized, very possibly \0.

Also, the Record objects you're creating are never being deleted, so this is leaking memory at each iteration.

Comments

1

elementToBeAdded->hotel_name[i] = 'a';

should be

elementToBeAdded->hotel_name[j] = 'a';

Comments

1

Because there is a mis-spelling in your source code above:

 for (int j = 0; j < NAME_LENGTH; j++)     
  elementToBeAdded->hotel_name[i] = 'a';

the index should be [j] here.

Comments

0

You got i and j mixed up:

for (int j = 0; j < NAME_LENGTH; j++)     
    elementToBeAdded->hotel_name[i] = 'a'; //<-- should be j here

You're also leaking memory, you should delete elementToBeAdded; at the end of the outer loop.

Comments

0

Now that you know the mistake, use std::fill_n instead which is in algorithm header.

#include <algorithm>

// .....

for (int i = 0; i < amount; i++) {         

   Record * elementToBeAdded = new Record;
   std::fill_n( elementToBeAdded->hotel_name, NAME_LENGTH-2, 'a' );
   elementToBeAdded->hotel_name[NAME_LENGTH-1] = '\0';         

   cout << "string-" << elementToBeAdded->hotel_name << "-\n\n";
   delete  elementToBeAdded;
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.