Page 1 of 1

Can't change text in a struct? O.o

PostPosted: Tue Nov 18, 2014 9:50 pm
by Hblade
For some reason game-editor keeps crashing when ever I try to change any text-based values inside a struct. For example:
Code: Select all
typedef struct {
    char*player_name;
               }profile;


I have a reason for using structs, and there's more variables inside the struct I just shortened it for the example. When ever I try to use sprintf, it crashes, when I use strcpy, nothing gets written O.o...

Code: Select all
strcpy(text, player_profile.player_name);

^ This part crashes it, trying to display the text.
Code: Select all
strcpy(player_profile.player_name, "example...");

^ This doesn't do anything O.o... Or if it does, I'm not able to display the output.

Re: Can't change text in a struct? O.o

PostPosted: Wed Nov 19, 2014 12:01 am
by digiot
Maybe, in the structure "player_profile", there is no variable "player_name",
or there is no such structure at all ?

Cheers!

Re: Can't change text in a struct? O.o

PostPosted: Wed Nov 19, 2014 12:33 am
by skydereign
That's because the char* isn't pointing to any memory. You would either need to allocate some memory for the char* or just use a char array.

Re: Can't change text in a struct? O.o

PostPosted: Wed Nov 19, 2014 4:30 am
by Hblade
Ahh ok thanks. I sort of found out how to do what I was trying to do without using structs though lol so yay O:

Re: Can't change text in a struct? O.o

PostPosted: Thu Jul 30, 2015 1:07 pm
by bat78
skydereign wrote:That's because the char* isn't pointing to any memory. You would either need to allocate some memory for the char* or just use a char array.

Not quite like so, skydereign.
It crashes exactly, because it DOES point to a memory, to an arbitrary memory address (obviously as the pointer points to a garbage value, since not initialized). Sometimes OS would not allow it, sometimes the memory address will not be accessible/immutable, sometimes it will not actually crash! This is a complete Undefined Behavior.

To make it safe, without causing it to crash, initialize it to 0.
Code: Select all
typedef struct { char* ptr; } mystruct;

Code: Select all
mystruct obj = { NULL };

In that case, this is the so called NULL Pointer and this is what actually literally doesn't point to anywhere. In that case It is very unlikely that will crash, especially on using strcpy, because such functions are designed to either return error or EOF if the pointer given on their argument is NULL and they will be unable to perform the task, therefore, nothing will be printed, copied or modified and the function will simply - fail :)