2015-01-11 76 views
1

我想创建一个固定大小的圆形数组,并且我想向它添加元素,然后应该能够打印它,当数组已满时,新添加的元素应该取代旧的元素C圆形阵列

例如

... 

list_add('a'); //add element 'a' 
list_add('b'); //add element 'b' 
list_add('c'); //add element 'c' 

list_print(); // should print 'a', 'b', 'c' 

list_add('d'); //add element 'd' 
list_add('e'); //add element 'e' 

list_print(); // should print 'c', 'd', 'e' 
... 

起初我以为,它会很容易与一些技巧,但它给了我一个头痛:( 这里是我做过什么

#include <stdio.h> 
#include <stdlib.h> 

void list_add(char element); 
void list_print(); 

char list[3] = {0, 0, 0}; 
int idx = 0; 

int main(){ 

    list_add('a'); 
    list_add('b'); 
    list_add('c'); 
    list_print(); 

    list_add('d'); 
    list_add('e'); 
    list_print(); 

    return 0; 
} 

void list_add(char element){ 
    list[idx] = element; 
    idx++; 
    if(idx==3) idx=0; 
} 
void list_print(){ 
    int i; 
    for (i=0;i<3;i++) printf("%c\n", list[i]); 
} 
+0

什么也正是你的问题?提示:使用模运算符。 – slnowak

+0

@slnowak我打印它们时的问题,订单错误 – acclav

+0

因为您只是遍历表格。你应该记住你当前的开始和结束位置在哪里。 – slnowak

回答

0
#define SIZE 3 
char list[SIZE] = {0}; 
//... 
void list_print(void){ 
    int n = SIZE; 
    int i = idx; 

    while(n--){ 
     printf("%c ", list[i++ % SIZE]); 
    } 
    printf("\n"); 
} 
+0

哇,你看起来好容易。迄今为止最好,最优雅的解决方案。 – acclav

0

有没有可能你没有注意到你的代码是好的?它的工作方式应该如此。您添加a,b,c。然后你添加d和e来循环替换数组:d,e,c。插图:

{0,0,0} 
{a,0,0} 
{a,b,0} 
{a,b,c} 
{d,b,c} 
{d,e,c} 

或者我在这里错过了什么?

这是你想要的方式吗?

int indicator = 0; 
<...> 
void list_add(char element) { 
    if((idx < 3) && !indicator) { 
    list[idx] = element; idx++; 
} else { 
    indicator = 1; 
    list[idx - 1] = element; idx--; 
    if (idx == 0) { 
     idx = 3; 
    } 
}; 

而现在呢? :)

void list_add(char element){ 
    if((idx < 3) && !indicator) { 
     list[idx] = element; idx++; 
    } else { 
     indicator = 1; 
     list[idx - 3] = list[idx - 2]; 
     list[idx - 2] = list[idx -1]; 
     list[idx - 1] = element; 
    }; 
} 

它通常填充数组直到3.然后它通过移动所有元素,然后插入一个新的值循环。如果你想创建一个动态数组,你将不得不为它添加一些动态(循环)。

+1

OP希望他的列表可以从最旧的条目打印到最新的条目。 – slnowak

+0

我明白了。但是,它不再是一个圈子。 – zilvinas

+0

as slnowak said,the output should be {c,d,e} from older to newest,maybe I called it wrong,因为我真的不知道它叫做什么:) – acclav

2

如果你想从最古老的元素打印出你的list_add代码和你的list_print

list_add“知道”,其中插入点,但list_print总是从0

你可能想从idx开始作为最古老的'元素开始。 我会检查它是否为0,因为它们在圆圈完成之前是“空”的插槽。

尝试:

void list_print(){ 
    int i=idx;//Start at the insertion point - just after the last insert - if any. 
    do{ 
     if(list[i]!=0){//Don't output unfilled entries. Just a suggestion. 
      //You can't now store 0 but that's probably OK for most purposes. 
      printf("%c\n", list[i]); 
     } 
     ++i;//Increment i and watch for looping like you did in list_add(). 
     if(i==3){ 
      i=0; 
     } 
    }while(i!=idx);//Stop when we're back at the beginning. 
} 
+1

你打我吧:)(+1) –

+0

你可以用i = i ++%size替换block; – slnowak

+1

@slnowak'我=我++%大小;'是错的。这可能是UB。 – BLUEPIXY