将一个字符串复制到另一个

时间:2012-01-04 10:39:05

标签: c

我在将文本传递给结构成员时遇到问题。 这是我的代码

#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

正如你可以看到&#34;播放器名称&#34;的结果是空的。 你还可以给我更优雅的方法来将文本设置为newobj.name吗? 我错过了什么?

1 个答案:

答案 0 :(得分:4)

代码中的strcpy错误(它将未初始化的数据复制到未分配的内存中)。你可能想要:

newobj.name = malloc(strlen(name) + 1);
strcpy(newobj.name, name);

或者更简单地说,如果你有strdup

newobj.name = strdup(name);