PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Registry Problems - TCHAR (Strings)

I have spent the past 5 hours trying to solve this problem, so I'm hoping that someone can help me.

I have a struct defined for the data that I want to load/save to the registry. For example, I have the following data for my high score data (score and player name):

Code:

typedef struct {
int Player1_Score;
int Player2_Score;
...
TCHAR Player1_Name[20];
TCHAR Player2_Name[20];
...
} RegistryData;

I can save/load the score (integer) data with no problems. But, when I try to load the TCHAR (string) data, I either get garbage or I get a fatal exception.

Here's my code to save the data to registry:

Code:

RegistryData saveprefs;

saveprefs.Player1_Score = Player1_Score;
saveprefs.Player2_Score = Player2_Score;
...
_tcsncpy(saveprefs.Player1_Name, Player1_Name, _tcslen((TCHAR *)Player1_Name));
_tcsncpy(saveprefs.Player2_Name, Player2_Name, _tcslen((TCHAR *)Player2_Name));
...

And, here's my code to load the data from the registry:

Code:

RegistryData loadprefs;

Player1_Score = loadprefs.Player1_Score;
Player2_Score = loadprefs.Player2_Score;
...
_tcsncpy(Player1_Name, loadprefs.Player1_Name, _tcslen((TCHAR *)loadprefs.Player1_Name));
_tcsncpy(Player2_Name, loadprefs.Player2_Name, _tcslen((TCHAR *)loadprefs.Player2_Name));
...

Once again, the integer data (Score) loads perfectly. It's the TCHAR (string) data for the player's name that is causing the problems.

I've spent way too much time on this already, so any help would be greatly appreciated!

Thanks...
:D
tcsncpy (and strncpy) copies maximum n bytes and not neccessary adds the tailing zero. in your case the zero char is never appended. read msdn for better description.
You're calling _tcsncpy incorrectly, the last arg should be _tcslen()+1 to include copying a NULL, since you're doing a _tcslen anyways, you should simply call _tcscpy which is easier, also you should check its length before copying it into your buffer since it may overflow if you don't. another good practice is to zero your destination array before copying into it.
I switched to _tcscpy and zeroed the destination array before the copy, and everything is working now!

Thanks for your help...I really do appreciate it!
:D