C 是否覆盖数组的所有元素,而不是仅覆盖一个?
我的鹅卵石手表里有一些C代码。它正在接收一些数据,每次作为一个键值对。它正在接收5条数据,每条数据都具有正确的键和值,如下所示:C 是否覆盖数组的所有元素,而不是仅覆盖一个?,c,arrays,pebble-watch,C,Arrays,Pebble Watch,我的鹅卵石手表里有一些C代码。它正在接收一些数据,每次作为一个键值对。它正在接收5条数据,每条数据都具有正确的键和值,如下所示: Key: 5 Value: '0' Key: 6 Value: '10' Key: 7 Value: '20' Key: 8 Value: '30' Key: 9 Value: '40' pebble一次接收其中一对,每次执行时都会调用以下函数(前一行:SimpleNuItem chats[5];) 然后将以下内容输出到pebble日志(我认为这是正确的): 因此,
Key: 5 Value: '0'
Key: 6 Value: '10'
Key: 7 Value: '20'
Key: 8 Value: '30'
Key: 9 Value: '40'
pebble一次接收其中一对,每次执行时都会调用以下函数(前一行:SimpleNuItem chats[5];
)
然后将以下内容输出到pebble日志(我认为这是正确的):
因此,尽管(对我来说)一切似乎都是正确的,但还是有一些意想不到的行为。与其让chat
成为每个元素具有不同值的SimpleNuItem
数组,相同的数据段(即最新的)将覆盖所有值,即使它(可能)应该只在指定的元素上写入。因此,在发送的5条数据结束时,整个聊天
数组最终被值40
的simpleNuitem
填充。我觉得这更像是一个C问题,而不是一个鹅卵石问题——但如果有人能解决这个问题,我将不胜感激
谢谢 正如注释中所回答的,您需要复制字符串,否则它们都指向内存中的同一地址并被覆盖
请参阅我对一个相关问题的回答:。似乎您将相同的内存重新用于
cstring
,然后您只复制指针,因此所有实例都具有相同的指针。如果cstring
确实指向以零结尾的字符串,您可能希望复制它,而不仅仅是复制指针。为此使用例如strdup
。请记住,在使用完重复的字符串后释放它。
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