Reputation: 23
I'm trying to use a function with an *char.
//the function
void init_player(struct player *_player, int pos_x, int pos_y, char *sprite){
printf(" %s",sprite);
_player->pos_x = pos_x;
_player->pos_y = pos_y;
strncpy(_player->player_sprite, sprite, sizeof(100));
}
When I print the function before using the funcion it is all right.
//the call
struct player array_player[3];
char *str = "img/dragon_verde.bmp";
printf("%s",str);
init_player(array_player[0],0,0,str);
Here are the print results:
Before function: img/dragon_verde.bmp
After function : )!Sjdnm
(something like that after function, can't copy it)
I hope you understand my English.
Upvotes: 0
Views: 59
Reputation: 1420
sizeof(100)
is not equal to value 100
. it's sizeof int
which is 4
.
when you use partial copy while strncpy you should manually append it with '\0'
at the end or it will cause undefined behavior.
change the size appropriately as per your needs. as other unwind said use sixeof the copying to string or send the number of characters to be copied when you call the function(as one of the parameter)
Check this it will give a idea of how to use strncpy.
Upvotes: 0
Reputation: 399793
This:
strncpy(_player->player_sprite, sprite, sizeof(100));
makes no sense, sizeof(100)
will evaluate to sizeof (int)
, probably 4 on most common platforms. Perhaps you thought of (size_t) 100
, which casts the integer 100 to the proper type for the third argument to strncpy()
: that's very redundant though and you should not write it like that. Just trust that implicit conversion from int
to size_t
of a value such as 100
will work.
The proper way to write it, if player_sprite
is a character array (i.e. there's something like char player_sprite[100];
inside the struct player
declaration, is:
strncpy(_player->player_sprite, sprite, sizeof _player->player_sprite);
Otherwise you need to find another way to have the proper buffer size.
Upvotes: 3
Reputation: 212949
You have a problem here:
init_player(array_player[0],0,0,str);
It should be:
init_player(&array_player[0],0,0,str);
Note that if you had enabled compiler warnings (and paid attention to them) you would have noticed the mistake immediately.
Upvotes: 2