Reputation: 570
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";
}
}
Upvotes: 2
Views: 144
Reputation: 341
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.
Upvotes: 1
Reputation: 34625
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;
}
Upvotes: 0
Reputation: 258
elementToBeAdded->hotel_name[i] = 'a';
should be
elementToBeAdded->hotel_name[j] = 'a';
Upvotes: 1
Reputation: 81684
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.
Upvotes: 2
Reputation: 2481
Because you have a typo in
elementToBeAdded->hotel_name[i] = 'a';
You mean j, not i.
Upvotes: 6
Reputation: 258608
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.
Upvotes: 0