在struct中添加char

时间:2015-01-23 18:29:10

标签: c arrays data-structures struct

为什么我无法将name添加到data函数中?

如果我运行此代码

data->userName = name;

该行是错误的。为什么我不能将userName设置为name

#import <Foundation/Foundation.h>
typedef struct User {
    char userName[5];
    int  userAge;
} User;
int roomNum = 0;
void data (User* data, int age, char* name);

main () {
    int age;
    char name[5];
    User list[10] = {};
    for (int i = 0; i<3; i++) {
        scanf("%d",&age);
        scanf("%s",name);

        data(&list[roomNum],age,name);
        roomNum ++;
    }

    NSLog(@"%d   %s",list[0].userAge,list [0].userName);
    NSLog(@"%d   %s",list[1].userAge,list[1].userName);
    NSLog(@"%d   %s",list[2].userAge,list[2].userName);
}

void data (User* data, int age, char* name){
    NSLog(@"%s",name);
    (*data).userAge = age;
    data->userName = name;
}

1 个答案:

答案 0 :(得分:1)

我建议一次更正,而不是这个

scanf("%s",name);

试试这个

scanf("%4s",name);
  /*    ^ should be sizeof(name) - 1 */

这样可以防止溢出name,并将值存储在结构中而不是

data->userName = name;

使用

strcpy(data->userName, name);

另外,你为什么要这样做

(*data).userAge = age;

使用一致的语法要么坚持上一行,要么

data->userAge = age;