简体   繁体   English

C-在数组混乱中存储结构

[英]C - Store Structs in Array confusion

Good morning, I am currently working on an app for Pebble Smartwatch which uses standard C, a language I just started with. 早上好,我目前正在为Pebble Smartwatch开发一个应用程序,该应用程序使用标准C(我刚开始使用的语言)。

I have a function that adds a Money Transaction to an array. 我有一个将资金交易添加到数组的功能。 I have defined Transaction like this: 我已经定义了这样的交易:

struct Transaction {
    char * title;
    char * amount;
    char * date;
    char * text;
} txnsArray[20];

whenever I receive a transaction it is added to the txnsArray using this function: 每当我收到交易时,都会使用以下功能将其添加到txnsArray中:

void addTransaction(DictionaryIterator * txnIter){
    Tuple *txnTitle_Tuple = dict_find(txnIter, TRANSACTION_TITLE);
    Tuple *txnAmount_Tuple = dict_find(txnIter, TRANSACTION_AMOUNT);
    Tuple *txnText_Tuple = dict_find(txnIter, TRANSACTION_TEXT);


    txnsArray[transOverview.txnCounter].title = txnTitle_Tuple->value->cstring;
    txnsArray[transOverview.txnCounter].amount = txnAmount_Tuple ->value->cstring;
    txnsArray[transOverview.txnCounter].text = txnText_Tuple->value->cstring;

    transOverview.txnCounter++;

}

Now when I check this array it does add entries as it is supposed to, however the last transaction I add applies to all entries. 现在,当我检查此数组时,它确实按预期添加了条目,但是我添加的最后一个事务适用于所有条目。

Say I first add a transaction wight he amount 2.5 € and then another one with 4.0€ then both entries will have 4.0€. 假设我先添加一笔交易权重,金额为2.5欧元,然后再添加一笔交易,金额为4.0欧元,那么两个条目的金额均为4.0欧元。

What am I doing wrong? 我究竟做错了什么? Help is much appreciated. 非常感谢您的帮助。 :) :)

It looks like the dict_find function does not allocate memory for value->cstring but uses the same buffer for each call. 看起来dict_find函数没有为value->cstring分配内存value->cstring而是为每个调用使用相同的缓冲区。 So the structs in your array end up with pointers to the same memory, and if dict_find modifies it, it modifies all array entries. 因此,数组中的结构以指向同一内存的指针结尾,如果dict_find修改,则它将修改所有数组条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM