2013-02-20 8 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]'를 사용할 필요가 없습니다. 4 칸만큼 들여 쓰고 그 다음에 코드를 들여 씁니다. – unwind

답변

1
  1. 당신은 enqueue 확실히 작동하지 않습니다. int rear = 0;을 선언하면 어떻게 될 수 있습니다. 즉, 항상 동일한 위치에 대기열에 포함됩니다.
  2. dequeue에는 아무 것도하지 않는 두 번의 malloc 호출이 있습니다. 그 결과로 아무 것도하지 않고, 그들은 단지 메모리 누출 일뿐입니다.
  3. headrear의 의미에 대해 생각해보고 문서화해야합니다. 그렇지 않으면 dequeue이 정확한지 말할 방법이 없습니다. 먼저 head을 증분 한 다음 q.strings[q.head]을 사용합니다. head이 대기열에있는 마지막 문자열의 위치라면 이것이 잘못되었습니다. - 늘리기 전에 문자열을 가져와야합니다.
  4. 당신은 결코 size을 감소시키지 않습니다. 이건 옳지 않아. 내 enquue 기능이 작동 확신
+0

내 문제를 깨달았다 고 생각합니다. Youre 맞습니다, 그것은 enqueue였습니다. 또한, 나는 다른 배열을 가리 키도록 결코 배열을 증가시키지 않았다. – user2014904

1

,

내가 대기열 이후 자신감을 (공유 할 수 없습니다)는 항상 q.strings에서의 저장소를 저장하기 위해 나타납니다. [1]

+0

이것은 내가 enqueue를 호출하는 방법입니다 (그리고 "엉성한 코드"에 대해 유감스럽게 생각합니다.) 나는 그 주석의 일부를 공동의 의미로 말했습니다 : for (int i = 0; i user2014904

관련 문제