0

I am learning how to use structures in an attempt to make a card game. I've been messing with this for roughly forever and I cannot get the printf statement to work how I would like. I think it has something to do with cc2 not being properly assigned to ctwo.typ but I'm really at a loss as to what to do about it.

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

typedef struct
{
    char typ[20];
    int num;
} card;

int main(void)
{
    char cc2[] = "Two of Clubs";

    card ctwo;
    ctwo.typ[20] = *cc2;
    ctwo.num = 2;

    //The output of the following is "Two of Clubs"
    printf("%s\n", cc2);

    //The output of the following is "2, "
    printf("%i, %s\n", ctwo.num, ctwo.typ);

    //The output of the following is "2, (null)" 
    printf("%i, %s\n", ctwo.num, ctwo.typ[0]);

return 0;
}
4

2 回答 2

3

您不能在 C 中分配数组。

您必须使用标准库函数复制字符strcpy()

card ctwo;
strcpy(ctwo.typ, "Two of Clubs");
ctwo.num = 2;

由于实际的字符串是常量(卡片不会更改其名称),您也可以const char *typ;在 中将其声明为普通struct字符串,只需将指针设置为字符串文字:

card ctwo;
ctwo.typ = "Two of Clubs";
ctwo.num = 2;

这不会复制实际的字符,它所做的只是将内存中“某处”存在的字符数组的地址分配给ctwo结构实例中的指针变量。

于 2013-07-06T17:43:41.250 回答
2

有几个问题,你不能分配给一个数组,你需要使用strcpy,这个:

ctwo.typ[20] = *cc2;

应该:

strcpy( ctwo.typ, cc2 ) ;

这个printf

printf("%i, %s\n", ctwo.num, ctwo.typ[0]);

应该:

printf("%i, %s\n", ctwo.num, ctwo.typ);

ctwo.typ[0]只是第一个字符,但您需要一个char *,当您使用%s 格式说明符时,它需要一个指向 C 样式字符串的指针,该字符串是一个终止的char数组null(以 a 结尾\0)。如果您想打印单个字符,您将使用%c格式说明符,然后ctwo.typ[0]将是有效的。

于 2013-07-06T17:46:48.963 回答