为什么我无法将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;
}
答案 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;