c - 数组的所有元素都被覆盖而不是仅一个元素?

标签 c arrays pebble-watch

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

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

卵石一次接收其中一对,每次执行时都会调用以下函数(上一行: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

因此,虽然(对我来说)一切似乎都是正确的,但还是存在意外的行为。 chat 不是每个元素具有不同值的 SimpleMenuItem 数组,而是相同的数据(即最新的)会覆盖所有值,即使它(可能)应该只写入指定的元素。因此,在发送 5 条数据结束时,整个 chats 数组最终会被值为 40SimpleMenuItem 填充。我觉得这更像是一个 C 问题,而不是具体的卵石问题 - 但如果有人能解决这个问题,我将非常感激。

谢谢!

最佳答案

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

请参阅我对相关问题的回复:Converting char array to string [and Pebble]

关于c - 数组的所有元素都被覆盖而不是仅一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535018/

相关文章:

objective-c - 多少()宏 objective-c

javascript - 在 ES6 中将多维数组转换为平面对象数组的最佳实践

c - Pebble C 将 char 转换为时间以在 double difftime(time_t end, time_t begin) 中使用

android - 我可以读取另一个应用程序内存吗?

c - Apache 日志 RSA 加密

c - gets() 和 scanf 之间的区别 ("%s")

PHP 数组无法正确从 php 文件中提取数据

c - 为什么我的 Pebble 表盘不是每分钟更新一次时间?

android - Android真的没有wchar_t吗?

arrays - 如何使用来自 Web 服务的数组填充 TableViewCell?