0
我將文本傳遞給結構成員時出現問題。 這裏是我的代碼將一個字符串複製到另一個
#include <stdio.h>
#include <string.h>
typedef struct {
char *name;
int rank;
int weapons;
}player;
player create_player(char name[], int rank, int weapons);
void display_player(player data);
int main (int argc, const char * argv[])
{
player tmp = create_player("First", 3, 3);
display_player(tmp);
}
player create_player(char name[], int rank, int weapons)
{
player newobj;
char *tmp = malloc(strlen(name) + 1);
strcpy(newobj.name, tmp);
newobj.rank = rank;
newobj.weapons = weapons;
free(tmp);
return newobj;
}
void display_player(player data)
{
printf("Player name %s\n", data.name);
printf("Player rang %d\n", data.rank);
printf("Player weapons %d", data.weapons);
}
這裏是輸出
Player name
Player rang 3
Player weapons 3
正如你所看到的「表演者姓名」的結果是空的。 也可以給我更優雅的方式來設置文本到newobj.name? 我想念什麼?
感謝。有用。我需要釋放malloc()還是自動釋放? – pr1m3x 2012-01-04 10:45:42
@ user1089415您需要自由,**停止使用後**。所以你不能在'printf'之前調用free。 – cnicutar 2012-01-04 10:46:21
我想我必須自由寫(newobj.name)嗎? – pr1m3x 2012-01-04 10:49:00