简体   繁体   English

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

[英]Copy one string to another

I have a problem passing text to structure member. 我在将文本传递给结构成员时遇到问题。 Here is my code 这是我的代码

#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);
}

And here is the output 这是输出

Player name 
Player rang 3
Player weapons 3

As you can see the result of "Player name" is empty. 如您所见,“玩家名称”的结果为空。 Also can you give me more elegant way to asign text to newobj.name ? 还可以给我一种更优雅的方式将文本分配给newobj.name吗? What I miss ? 我想念什么?

The strcpy in your code is wrong (it copies uninitialized data into unallocated memory). 您代码中的strcpy错误(它将未初始化的数据复制到未分配的内存中)。 You probably want: 您可能想要:

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

Or more simply, if you have strdup : 更简单地说,如果您有strdup

newobj.name = strdup(name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM