我已将用户的结构定义为USER:
struct user {
char *name;
int age;
};
typedef struct user USER;
我可以创建一个用户数组:
USER uArray[3] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 }
};
现在我该如何将预定义用户添加到用户列表中?:
USER u1 = { "Dave", 78 };
我假设您可以将其添加到列表中,如下所示。但是,会返回一个错误,指出它无法从“USER”转换为“char *”。
USER uArray[4] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 },
u1
};
据我所知,它将u1视为创建用户的第一个元素(name = u1),那么您如何将预定义用户添加到用户数组中呢?
代码正在运行:
#include <stdio.h>
struct user {
char *name;
int age;
};
typedef struct user USER;
void changeName(USER *u);
void main(void)
{
USER u1 = { "Dave", 78 };
USER uArray[4] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 }
};
// add u1 to position 3 of the array
uArray[3] = u1;
for (int i = 0; i < 4; i++)
{
if (uArray[i].name == "Bob")
{
changeName(&uArray[i]);
}
printf("User: %d, Name: %s, Age: %d\n", i, uArray[i].name, uArray[i].age);
}
}
void changeName(USER *u)
{
u->name = "Dave";
}
答案 0 :(得分:1)
#include <stdio.h>
struct user {
char *name;
int age;
};
typedef struct user USER;
USER u1 = { "Dave", 78 };
USER uArray[4] = {
{ "Allan", 12 },
{ "Bob", 34 },
{ "Chris", 56 }
};
int main()
{
int i;
uArray[3] = u1;
for (i = 0; i < 4; ++i)
{
printf("%s: %d\n", uArray[i].name, uArray[i].age);
}
return 0;
}