Linas
Linas

Reputation: 570

String initialization fails

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

Answers (6)

Guangchun
Guangchun

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

Mahesh
Mahesh

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

codetantra
codetantra

Reputation: 258

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

should be

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

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

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

DRVic
DRVic

Reputation: 2481

Because you have a typo in

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

You mean j, not i.

Upvotes: 6

Luchian Grigore
Luchian Grigore

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

Related Questions