[英]How to properly use struct in this case
I am new to programming in C and I am trying to figure out the correct use of the struct, as an example: 我是C语言编程的新手,我试图找出该结构的正确用法,例如:
int main (int argc, char *argv[])
{
char player_one = "bob";
char player_two = "steve";
enum colour
{
P_RED, P_WHITE
};
struct player
{
char name[MAX_NAME_LEN+1];
enum colour col;
};
int rndNumber;
srand (time(NULL));
rndNumber = rand() % 2;
struct player p1 = {player_one, rndNumber};
struct player p2 = {player_two, rndNumber};
printf("%s\n", p1.name);
printf("%d\n", p1.col);
printf("%s\n", p2.name);
printf("%d\n", p2.col);
return EXIT_SUCCESS;
}
when I try to compile this code I get several errors. 当我尝试编译此代码时,出现几个错误。
warning: initialization makes integer from pointer without a cast [enabled by default]
char player_one = "bob";
warning: missing braces around initializer [-Wmissing-braces]
struct player p1 = {player_one, rndNumber};
warning: (near initialization for ‘p1.name’) [-Wmissing-braces]
warning: initializer element is not computable at load time [enabled by default]
warning: ISO C90 forbids mixed declarations and code [-Wpedantic]
struct player p1 = {player_one, rndNumber};
which are making it so that p1.name and p2.name print nothing and p1.col and p2.col always print 0 even though rndNumber successfully prints random numbers. 这使得p1.name和p2.name不打印任何内容,而p1.col和p2.col始终打印0,即使rndNumber成功打印了随机数。 So what am I doing wrong here?
那我在做什么错呢? oO
OO
In C, strings are not characters, but arrays of characters. 在C语言中,字符串不是字符,而是字符数组。 So declare them like this:
因此,像这样声明它们:
char *player_one = "bob";
or 要么
char player_one[] = "bob";
Secondly, in the structure you can either declare the string as: 其次,您可以在结构中将字符串声明为:
char name[MAX_NAME_LEN+1];
or 要么
char *name;
The difference is that in the first case, MAX_NAME_LEN+1
characters are allocated, in the second case name
is just a pointer. 区别在于,在第一种情况下,分配了
MAX_NAME_LEN+1
字符,在第二种情况下, name
仅是一个指针。 So in the first case, you need to copy stings: 因此,在第一种情况下,您需要复制字符串:
strcpy(p1.name, player_one);
in the second case, assignment will do: 在第二种情况下,分配将执行以下操作:
p1.name = player_one;
or as you have done it: 或如您所愿:
p1 = {player_one, rndNumber};
First of all, define the new types outside the main() function: 首先,在main()函数之外定义新类型:
#define MAX_NAME_LEN 100
typedef enum
{
RED, WHITE
} Color;
typedef struct
{
char *name;
Color color;
} Player;
Then, in the main() function, you can use the new types like this: 然后,在main()函数中,可以使用如下新类型:
char *player_one = "bob";
char *player_two = "steve";
Color redColor = RED;
Color whiteColor2 = WHITE;
Player p1 = { player_one, redColor };
Player p2 = { player_two, whiteColor2 };
printf("%s\n", p1.name);
printf("%d\n", p1.color);
printf("%s\n", p2.name);
printf("%d\n", p2.color);
p1.name = "john";
p2.color = RED;
printf("%s\n", p1.name);
printf("%d\n", p1.color);
printf("%s\n", p2.name);
printf("%d\n", p2.color);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.