【问题标题】:All elements of array overwritten instead of only one?数组的所有元素都被覆盖而不是只有一个?
【发布时间】:2023-03-11 20:40:01
【问题描述】:

我的 pebble 手表中运行了一些 C 代码。它每次都以键值对的形式接收一些数据。它正在接收 5 条数据,每条数据都有正确的键和值,如下所示:

Key: 5 Value: '0'
Key: 6 Value: '10'
Key: 7 Value: '20'
Key: 8 Value: '30'
Key: 9 Value: '40'

pebble 一次接收其中一对,每次执行时都会调用以下函数(上一行:SimpleMenuItem chats[5];

void in_received_handler(DictionaryIterator *received, void *context) {
    dataReceived = dict_read_first(received);
    APP_LOG(APP_LOG_LEVEL_DEBUG, "read first");
    while (dataReceived != NULL){

        APP_LOG(APP_LOG_LEVEL_DEBUG, dataReceived->value->cstring);
        char keystr[10];
        snprintf(keystr, 10, "Key: %d", (int)dataReceived->key);
        APP_LOG(APP_LOG_LEVEL_DEBUG, keystr);

        snprintf(keystr, 10, "Index: %d", (int)dataReceived->key -5);
        APP_LOG(APP_LOG_LEVEL_DEBUG, keystr);
        chats[dataReceived->key - 5] = (SimpleMenuItem){
                    // You should give each menu item a title and callback
                    .title = dataReceived->value->cstring,
                    .callback = selected_chat,
                };

        dataReceived = dict_read_next(received);
        APP_LOG(APP_LOG_LEVEL_DEBUG, "read again");
    }

    layer_mark_dirty((Layer *)instant_chats);
}

然后将以下内容输出到卵石日志(这是我认为正确的):

[DEBUG] sr.c:195: read first
[DEBUG] sr.c:197: 0
[DEBUG] sr.c:200: Key: 5
[DEBUG] sr.c:219: Index: 0
[DEBUG] sr.c:243: read again
[DEBUG] sr.c:195: read first
[DEBUG] sr.c:197: 10
[DEBUG] sr.c:200: Key: 6
[DEBUG] sr.c:219: Index: 1
[DEBUG] sr.c:243: read again
[DEBUG] sr.c:195: read first
[DEBUG] sr.c:197: 20
[DEBUG] sr.c:200: Key: 7
[DEBUG] sr.c:219: Index: 2
[DEBUG] sr.c:243: read again
[DEBUG] sr.c:195: read first
[DEBUG] sr.c:197: 30
[DEBUG] sr.c:200: Key: 8
[DEBUG] sr.c:219: Index: 3
[DEBUG] sr.c:243: read again
[DEBUG] sr.c:195: read first
[DEBUG] sr.c:197: 40
[DEBUG] sr.c:200: Key: 9
[DEBUG] sr.c:219: Index: 4
[DEBUG] sr.c:243: read again

所以,虽然一切似乎都是正确的(对我来说),但还是有意外的行为。而不是让chats 成为SimpleMenuItem 的数组,每个元素具有不同的值,相同的数据(即最新的)覆盖所有值,即使它(可能)应该只写在指定的元素上。因此,在发送 5 条数据的末尾,整个 chats 数组最终被填充为 SimpleMenuItem40。我觉得这更像是一个 C 问题,而不是一个 pebble 问题——但如果有人能解决这个问题,我将不胜感激。

谢谢!

【问题讨论】:

  • 看来你为cstring重用了相同的内存,然后你只复制了指针,所以所有实例都有相同的指针。如果cstring 确实指向一个以零结尾的字符串,您可能想要复制 它而不是仅仅复制指针。使用例如strdup 为此。完成后记得释放重复的字符串。

标签: c arrays pebble-watch


【解决方案1】:

正如 cmets 中的回答,您需要复制字符串,否则它们都指向内存中的相同地址并被覆盖。

查看我对相关问题的回复:Converting char array to string [and Pebble]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多