使用指针赋予struct功能

时间:2013-12-06 01:18:09

标签: c function pointers struct scanf

在C中我试图使用结构来存储播放器的当前数据,我在结构中管理:

#include <stdio.h>
#include <stdlib.h>

typedef struct playerdat{
  char playername[20];
  int maxhp;
}playerdat;

void new_game(struct playerdat *player){

  printf("Enter your character's name: \n");
  scanf("%s", &player->playername);
  player->playername = strcpy("Little", player->playername);
}

int main(){

  struct playerdat player;
  new_game(&player);

  return 0;
}

一切正常,直到我尝试更改结构的元素。

错误消息显示为:错误:从类型'char *'

中键入'char [20]'类型时的incompativle类型

你能告诉我一个如何在这里使用指针的例子吗? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

scanf("%s", &player->playername);//don't need &
player->playername = strcpy("Little", player->playername);//you know,the memeber `playername` is a array,`playername` is the name of the array,so you can't modify the name of a array

答案 1 :(得分:0)

不要使用&amp;在scanf上使用char。

    #include<stdio.h>
    int main()
    {
        char name[20];
        int age;
        printf ("Enter your family name: ");
        scanf ("%s",name); //notice here no &
        printf ("Enter your age: ");
        scanf ("%d",&age);  // here comes &
        return 0;
    }