나는 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;
}
다음 두 답변은 적절한 작동을 위해 모두 필요합니다 .-) – anishsane
동의, 모두 변경해야합니다. 그러나 pop 함수는 여전히 나에게 분할 오류를 제공합니다. 왜 확실하지 ... – KishB87