2013-02-20 69 views
0

好吧夥計們。我可以看到我正在做的這個項目的終點線。我試圖找出爲什麼當我嘗試返回值(即出列)數組時,爲什麼我的數組吐出NULLS。我相信我的enquue函數可以工作,並且也確信它將從地址指針指的是。這是我的代碼。我故意沒有包含我的主要功能,僅僅是因爲我不想讓電路板超載。但是,如果需要查看診斷問題,請告訴我。需要與陣列排隊

#include <assert.h> 
#include <stdbool.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

// the capacity of the queue 
#define CAPACITY 10 

// a queue 
typedef struct 
{ 
    // the index of the first element in the queue 
    int head; 

    // storage for the elements in the queue 
    char* strings[CAPACITY]; 

    // the size of the queue 
    int size; 
} 
queue; 

// declare a queue (as a global variable) 
queue q; 

/* 
* Puts a new element into the queue into the "end" of the data structure 
* so that it will be retrived after the other elements already in the 
* queue. 
*/ 
bool enqueue(char* str) 
{ 
    int rear = 0; // back of the queue 

    if (q.size==CAPACITY)   
    { 
     return false; 
    } 
    else 
    { 
     rear = (rear + 1) % CAPACITY; 
     q.strings[rear] = str; 
     printf("%s", q.strings[rear]); 

     q.size++; 
     return true; 
    } 
} 

/** 
* Retrieves ("dequeues") the first element in the queue, following the 
* the "first-in, first-out" (FIFO) ordering of the data structure. 
* Reduces the size of the queue and adjusts the head to the next element. 
*/ 
char* dequeue(void) 
{ 
    char *charHead = NULL; 
    if (q.size) 
    { 
     charHead = malloc(sizeof(char)) ; 
     char *chpointer = malloc(sizeof(strArray[12])); 
     q.head++; 
     q.head = q.head%CAPACITY; 
     charHead = q.strings[q.head]; 
     return charHead;   
    }  
    // Return null character if queue is empty 
    return NULL; 
} 
+0

什麼是'strArray'?並且請嘗試縮進更好,不需要使用'[code]',只需縮進四個空格,然後再正確縮進代碼。 – unwind 2013-02-20 07:50:43

回答

1
  1. enqueue肯定是行不通的。它怎麼可能,當它聲明int rear = 0;,這意味着它總是排隊在相同的位置。
  2. 你的dequeue有兩個malloc調用,似乎沒有做任何事情。你不會對他們的結果做任何事情,他們只是內存泄漏。
  3. 您應該考慮headrear的意思,並記錄下來。否則,無法說明dequeue是否正確。首先增加head,然後取q.strings[q.head]。如果head是排隊的最後一個字符串的位置,則這是錯誤的 - 您應該在增加之前取出字符串。
  4. 您永遠不會遞減size。這不可能是正確的。
+0

我想我意識到我的問題。你是對的,這是入隊。此外,我從來沒有增加我的數組,所以它指向另一個下標。 – user2014904 2013-02-20 16:56:00

1

我相信我的enquue功能工作,

我不能共享,因爲排隊的信心()似乎總是存儲它的商店在q.strings [1]。

+0

這就是我打電話入隊的方式(對於「粗糙的代碼」我很抱歉。)我的意思是:爲某些東西提供合作評論: for(int i = 0; i user2014904 2013-02-20 15:42:46