2013-11-25 2 views
1

나는 push와 pop 함수로 간단한 스택을 만들고있다. 일련의 문자열을 메모리 스택 역할을하는 배열로 푸시하려고합니다. 그러나 GDB는 배열에 문자열을 올바르게 복사하지 않았다는 것을 계속해서 보여줍니다. 누구든지이 문제를 해결할 수있는 방법에 대한 아이디어가 있습니까?C에서 문자열을 배열에 복사하는 방법은 무엇입니까?

char* pop(void) 
{ 
    int i = CAPACITY-1; // i is the same! 
    return s.strings[i--]; // the same pointer 
} 

나는 다음에 그것을 변경 제안하고 싶습니다 :

/************************************************************************* 
* stack.c 
* 
* Implements a simple stack structure for char* s. 
************************************************************************/ 

// for strdup() in the testing code 
#define _XOPEN_SOURCE 500 

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

// the capacity of the stack 
#define CAPACITY 10 

//global variable used to keep track of pop and push 

typedef struct 
{ 
    // storage for the elements in the stack 
    char* strings[CAPACITY]; 

    // the number of elements currently in the stack 
    int size; 
} stack; 

// declare a stack (as a global variable) 
stack s; 

/** 
* Puts a new element into the stack onto the "top" of the data structure 
* so that it will be retrived prior to the elements already in the stack. 
*/ 
bool push(char* str) 
{ 
    int i = 0; 
    s.strings[i++] = strdup(str); 
    ++s.size; 
    return false; 
} 

/** 
* Retrieves ("pops") the last ("top") element off of the stack, following 
* the "last-in, first-out" (LIFO) ordering of the data structure. Reduces 
* the size of the stack. 
*/ 
char* pop(void) 
{ 
    int i = CAPACITY-1; 
    return s.strings[i--]; 
} 

/** 
* Implements some simple test code for our stack 
*/ 
int main(void) 
{ 
    // initialize the stack 
    s.size = 0; 

    printf("Pushing %d strings onto the stack...", CAPACITY); 
    for (int i = 0; i < CAPACITY; i++) 
    { 
     char str[12]; 
     sprintf(str, "%d", i); 
     push(strdup(str)); 
    } 
    printf("done!\n"); 

    printf("Making sure that the stack size is indeed %d...", CAPACITY); 
    assert(s.size == CAPACITY); 
    printf("good!\n"); 

    printf("Making sure that push() now returns false..."); 
    assert(!push("too much!")); 
    printf("good!\n"); 

    printf("Popping everything off of the stack..."); 
    char* str_array[CAPACITY]; 
    for (int i = 0; i < CAPACITY; i++) 
    { 
     str_array[i] = pop(); 
    } 
    printf("done!\n"); 

    printf("Making sure that pop() returned values in LIFO order..."); 
    for (int i = 0; i < CAPACITY; i++) 
    { 
     char str[12]; 
     sprintf(str, "%d", CAPACITY - i - 1); 
     assert(strcmp(str_array[i], str) == 0); 
     free(str_array[i]); 
    } 
    printf("good!\n"); 

    printf("Making sure that the stack is now empty..."); 
    assert(s.size == 0); 
    printf("good!\n"); 

    printf("Making sure that pop() now returns NULL..."); 
    assert(pop() == NULL); 
    printf("good!\n"); 

    printf("\n********\nSuccess!\n********\n"); 

    return 0; 
} 
+1

다음 두 답변은 적절한 작동을 위해 모두 필요합니다 .-) – anishsane

+0

동의, 모두 변경해야합니다. 그러나 pop 함수는 여전히 나에게 분할 오류를 제공합니다. 왜 확실하지 ... – KishB87

답변

1

팝() 함수 항상 같은 문자열을 반환

char* pop(void) 
{ 
    if (s.size == 0) return NULL; 
    char *str = s.strings[--s.size]; 
    s.strings[s.size] = NULL; 
    return str; 
} 

를이 쓸모없는 포인터를 스택에 저장하지 않아도됩니다.

+0

흠, 재미있는 포인트와 그 입력에 대한 감사. 나는 그것을 깨닫지 못했다. 그러나 제안을 삽입 한 후에도 프로그램이 계속 실행되지 않습니다. 푸시 기능에 문제가 있다고 생각합니다. s.strings 배열이 문자열을 제대로 저장하고 있다고 생각하지 않습니다. – KishB87

1

귀하의 푸시 기능이 항상 0

변경과 같이 위치에 문자열을 삽입합니다

bool push(char* str) 
{ 
    if (s.size == CAPACITY) return true; // Stack is full! 
    s.strings[s.size++] = strdup(str); 
    return false; 
} 

그리고 팝

(나는 마이클스 응답에서이 훔친 빈 스택 가드 추가) :

char* pop(void) 
{ 
    if (s.size == 0) return NULL; // Stack is empty! 
    char *str = s.strings[--s.size]; 
    s.strings[s.size] = NULL; 
    return str; 
} 
+0

프로그램에서 큰 문제가 해결되었습니다. 자, 유일한 문제는 팝입니다 ... 지금 당장은, 나는 세분화 오류가 발생합니다 ... 왜 그런지 모르겠군요. – KishB87

+0

Michaels 대답을 참조하십시오.하지만 스택이 비어 있는지 확인하려면 체크를 추가해야합니다. –

+1

두 번 호출하면 메모리 누수가 발생하므로 "strdup"하나를 제거하는 것이 좋습니다. 예를 들어, push() 또는 push() 호출에서 제거 할 수 있습니다. 또한 내 pop(), push()를이 대답에서 사용하고 고정 된 어설 션 조건을 78 줄에 실행합니다. 프로그램이 정상적으로 실행됩니다. – Michael

관련 문제