I've got a sorting function which should put all usernames starting from 3 character or more to the top of the array, and all the ones under 3
if(wcslen((WCHAR*)playerNames[i]) < 3)
(Which will all be "-") to the bottom and replaced with <Unknown>
. I've tried the following but I sets weird debugger values when replacing "-"
with "<Unknown>"
and crashes.
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];
}
}
This should return
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>
EDIT: Tried the following, but I still don't get it to work:
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];
}
}
Here's one problem: if (playerNames[i] != "-"){
will never execute the true
branch because you're performing a pointer comparison, not a value comparison (C++ is not like Javascript or C#). You're comparing the memory address of a string in playerNames
with the address of the literal string "-"
.
Also a few other points:
static_cast
, dynamic_cast
or reinterpret_cast
instead as needed).playerNames
has 30 elements but sorted
has 29 elements. Why is there a difference?sorted
has function scope lifetime. Once sort
returns any pointer to sorted
is invalid and the data will likely be overwritten by a subsequent function call or stack allocation.