【问题标题】:how do I assign a value to a struct array inside a struct in c?如何在c中的结构内为结构数组赋值?
【发布时间】:2021-02-23 07:40:06
【问题描述】:

所以我需要将扫描的值分配给变量palo和valor,它们属于cartas这是一个结构,而这个在另一个结构内?

这是我到目前为止所得到的,我收到一个错误“必须具有指向对象类型的指针”:

#include <stdio.h>
#define DIM 100

typedef struct{
    char palo;
    int  valor;
}t_carta;

typedef struct{
    int ncartas;
    t_carta cartas[DIM];
}t_baraja;

int main(){
    t_baraja b1;
    t_carta carta[DIM][DIM];

    printf("Cuantas cartas tiene su baraja? ");
    scanf("%d", &b1.ncartas);
    printf("Introduzca las cartas separadas por guiones (o4-e10-b1...):\n");
    for(int i=0; i<b1.ncartas; i++){
        scanf("%c%d%*c", &b1.cartas->palo, &b1.cartas->valor);
        b1.cartas[i][i]=b1.cartas->valor;
    }

    return 0;
}```

【问题讨论】:

  • @martiwg 数据成员 t_carta cartas[DIM];是一维数组。那么为什么要使用两个索引 b1.cartas[i][i]=b1.cartas->valor;?这种说法没有意义。
  • @martiwg 这个数组是什么 t_carta carta[DIM][DIM];在做什么?
  • @VladfromMoscow 我不知道我的老师将其作为标题发送,并且并不真正了解如何将值分配给变量,但您的回复解决了这一切! tysm

标签: arrays c struct variable-assignment


【解决方案1】:

提供的代码没有意义,但回答您的问题

如何在 c 中为结构体中的结构体数组赋值?

我将解释如何做到这一点。

如果你有一个像这样声明的对象

t_baraja b1;

然后设置其数据成员数组的数据成员

 t_carta cartas[DIM];

你可以通过以下方式

b1.cartas[i].palo; = some_value;
b1.cartas[i]valor = another_value;.

其中i 是选择数据成员数组cartas 中的元素的索引。

【讨论】:

  • 谢谢!我知道这没有意义,所以这就是我问的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 2015-12-20
  • 2016-06-16
  • 1970-01-01
相关资源
最近更新 更多