更新Arduino中的结构

时间:2017-11-14 07:18:11

标签: c

我在Arduino中有一个如下所示的结构,我想更新它

struct record
{
   int bookId;
   int qtyInStock;

};

typedef struct record Record;

Record aRec;
aRec.bookId = 100;
aRec.qtyInStock = 12;

aRec.bookId = 101;
aRec.qtyInStock = 10;

aRec.bookId = 102;
aRec.qtyInStock = 100;

如果出售bookId 101,那我该如何更新qtyInStock?所以,qtyInStock for bookId 101现在应该是9。

由于

2 个答案:

答案 0 :(得分:0)

我会将所有记录保存在链接列表中,并迭代它们,找到书籍ID,减少它的可用计数。

您知道您正在编写示例代码中的单个记录(aRec)吗?你将需要某种容器:

struct node {
   Record* value;
   Node* next;
}

sruct recordList {
    Node* head;
}
/* ... */

答案 1 :(得分:0)

您可以使用类型记录数组来存储多本书籍。作为内置功能出售,您可以试试这个:

struct record
{
   int bookId;
   int qtyInStock;

};
typedef struct record Record;
void sold(int id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
      records[i].qtyInStock--;
    }
  }
}
void updateId(int id, int new_id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].bookid = new_id;
    }
  }
}
void updateQty(int id, int new_qty, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].qtyInStock = new_qty;
    }
  }
}
void main() {
  Record records[3];
  records[0].bookId = 100;
  records[0].qtyInStock = 12;
  records[1].bookId = 101;
  records[1].qtyInStock = 10;
  records[2].bookId = 102;
  records[2].qtyInStock = 100;
  int i;
  sold(101, records);
  updateId(100, 99, records);
  updateQty(102, 15, records);
  for(i=0;i<3;i++) {
    printf("%d\n", records[i].bookId);
    printf("%d\n\n", records[i].qtyInStock);
  }
}