2015-01-11 77 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