我想将字符串数组中的每个字符串向左移动一个元素:
char historyArray[HISTORY_DEPTH][COMMAND_LENGTH];
我下面的两次尝试都没有工作。有人可以向我解释我做错了什么吗?
for (int i = 1; i < HISTORY_DEPTH; i++) {
strcpy(historyArray[i-1], historyArray[i]);
}
for (int i = 1; i < HISTORY_DEPTH; i++) {
historyArray[i-1] = historyArray[i];
}
将historyArray定义为,char *historyArray[HISTORY_DEPTH];
将historyArray定义为字符串指针的数组。然后,historyArray [0]指向teststring
分配的结果。作为指针数组,您可以正确处理每个字符串指针。然后,您可以分配一个缓冲区指针以用作数组中的元素。并使用strcpy复制到该缓冲区。
char *historyArray[HISTORY_DEPTH];
// put initialization code here
for (int i = 1; i < HISTORY_DEPTH; i++) {
historyArray[i-1] = historyArray[i];
}
historyArray[HISTORY_DEPTH-1] = NULL; //empty the last element pointer
现在,这会将指针移到数组的上一个元素中。
请注意,historyArray [0]的原始内容现在已丢失,如果使用malloc创建它,则将导致内存泄漏。结果,它应该已经free()
应用了它。如果它是一个固定缓冲区,不需要释放,那么您不必担心它。
char historyArray[HISTORY_DEPTH][MAX_SIZE];
for (int i = 1; i < HISTORY_DEPTH; i++) {
// Or use the memset with strlen(size+1)
// to ensure that the ending '\0' is also copied
strcpy(historyArray[i-1], historyArray[i]);
}
historyArray[HISTORY_DEPTH-1][0] = '\0'; // make the last an empty string
第二个字符串的strcpy会将historyArray指向的每个字符串的内容复制到前一个元素指向的缓冲区中,而无需移动指针本身。假定每个缓冲区足够大以容纳字符串。除非您输入空字符串,否则最后一个指针将继续保持与以前相同的数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句