这是我的计划。输出应该是'a'字符的序列,但由于某种原因,它不是。为什么呢?
#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";
}
}
答案 0 :(得分:6)
因为你有错字
elementToBeAdded->hotel_name[i] = 'a';
你的意思是j,而不是我。
答案 1 :(得分:2)
当肯定打算使用i
时,您的最内层循环正在使用j
:
elementToBeAdded->hotel_name[i] = 'a';
因此,您永远不会设置Record
#1的char[]
的第0个元素,也不会设置Record
#2的第1个元素等。这意味着每个通过最外层循环的时间除了第一个,酒店名称中的第一个char
将保持未初始化状态,很可能是\0
。
此外,您正在创建的Record
对象永远不会被删除,因此这会在每次迭代时泄漏内存。
答案 2 :(得分:1)
elementToBeAdded->hotel_name[i] = 'a';
应该是
elementToBeAdded->hotel_name[j] = 'a';
答案 3 :(得分:1)
因为上面的源代码中存在拼写错误:
for (int j = 0; j < NAME_LENGTH; j++)
elementToBeAdded->hotel_name[i] = 'a';
索引应该是[j]。
答案 4 :(得分:0)
您i
和j
混淆了:
for (int j = 0; j < NAME_LENGTH; j++)
elementToBeAdded->hotel_name[i] = 'a'; //<-- should be j here
你也在泄漏内存,你应该在外循环结束时delete elementToBeAdded;
。
答案 5 :(得分:0)
现在您已经知道错误,请使用std::fill_n
代替算法标题中的内容。
#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;
}