我有一个排序功能,它应该将所有用户名从3个字符或更多字符开始到数组的顶部,所有的用户名都在3以下
if(wcslen((WCHAR*)playerNames[i]) < 3)
(将全部为“ - ”)到底部并替换为<Unknown>
。我尝试过以下操作,但在用"-"
替换"<Unknown>"
并崩溃时,我设置了奇怪的调试器值。
char* playerNames[30] = { "Player1", "Player2", "Player3", "Player4", "Player5", "Player6", "-", "Player7", "-", "-", "-", "-", "Player8", "Player9", "Player10", "Player11", "Player12", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "Player14", "Player15" };
void sort(){
char* sorted[29];
int slot = 0;
for (int i = 0; i < 30; i++){
if (playerNames[i] != "-"){
if (i == slot){
sorted[slot] = playerNames[i];
}
else {
sorted[i] = playerNames[i];
}
slot++;
}
else if (playerNames[i] == "-"){
slot++;
}
}
for (int i = 0; i < 30; i++){
if (wcslen((WCHAR*)sorted[i]) < 3){
sorted[i] = "<Unknown>";
}
playerNames[i] = sorted[i];
}
}
这应该返回
Player1
Player2
Player3
Player4
Player5
Player6
Player7
Player8
Player9
Player10
Player11
Player12
Player13
Player14
Player15
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
<Unknown>
编辑:试过以下内容,但我仍然没有让它发挥作用:
void sort(){
char* sorted[30];
int slot = 0;
for (int i = 0; i < 30; i++){
if (strcmp(playerNames[i], "-") != 0){
if (i == slot){
sorted[slot] = playerNames[i];
}
else {
sorted[i] = playerNames[i];
}
slot++;
}
else if (playerNames[i] == "-"){
slot++;
}
}
for (int i = 0; i < 30; i++){
if (strlen(sorted[i]) < 3){
sorted[i] = "<Unknown>";
}
playerNames[i] = sorted[i];
}
}
答案 0 :(得分:1)
以下是一个问题:true
永远不会执行playerNames
分支,因为您正在执行指针比较,而不是值比较(C ++不像Javascript或C#) 。您将"-"
中字符串的内存地址与文字字符串static_cast
的地址进行比较。
还有其他几点:
dynamic_cast
,reinterpret_cast
或playerNames
)。sorted
有30个元素,但sorted
有29个元素。为什么会有区别?sort
具有功能范围生命周期。一旦sorted
返回任何指向stack()
的指针无效,数据很可能被后续函数调用或堆栈分配覆盖。