简体   繁体   English

在C语言中构造堆栈数据结构的指针

[英]Pointers to Structs Implementation of Stack Data Structure in C

I've created a Stack structure in C. When the stack is initialized with a value, I am able to print it back and receive the correct output. 我在C中创建了一个Stack结构。当使用值初始化堆栈时,我能够将其打印回来并接收正确的输出。 However, after pushing a new string, the print function prints what appears to be a random character (ASCII 177). 但是,在推送新字符串后,打印功能会打印出似乎是随机字符的内容(ASCII 177)。

Originally, I implemented this project with pointers, but I was unable to get it working. 最初,我用指针实现了这个项目,但是我无法让它工作。 Instead, I opted to only use a pointer for the Node *nodes member of Stack . 相反,我选择仅使用指针作为StackNode *nodes成员。 That way, when I need to grow the stack, I can just multiply the amount of memory required by Stack.size . 这样,当我需要增加堆栈时,我可以将Stack.size所需的内存量相乘。 However, this approach has not worked yet either. 但是,这种方法还没有奏效。

#define MAX_DATA 64
struct Node{
    char val[MAX_DATA];
};

struct Stack{
    int size;
    struct Node *nodes;
};

These are used as follows: 这些用法如下:

struct Node node = {.val = "Test"};
struct Stack stack = newStack(node);
printStack(stack);

The newStack function initializes nodes properly. newStack函数正确初始化nodes For the sake of inclusion: 为了包含:

struct Stack newStack(struct Node node)
{
    struct Stack stack;
    stack.size = 1;
    stack.nodes = (struct Node*) malloc(sizeof(struct Node));
    stack.nodes[0] = node;
    return stack;
}

The stack is then printed iteratively in printStack() , with stack.size being the upper bound of the for-loop. 然后在printStack()迭代打印堆栈, stack.size是for循环的上限。

The trouble comes when I try to run: 当我尝试运行时出现问题:

struct Node node2 = {.val = "Test1"};
push(stack, node2);
printStack(stack);

The push function aims to create a temporary stack and assign the value of the stack to it. push函数旨在创建一个临时堆栈并为其分配堆栈的值。 After this, the size is incremented, the pointer to the nodes is freed, and new memory is allocated, with room for a new member at the end. 在此之后, size递增,释放指向nodes的指针,并分配新内存,最后为新成员留出空间。

void push(struct Stack stack, struct Node node)
{
    struct Stack temp_stack = stack;
    stack.size += 1;
    free(stack.nodes);
    stack.nodes = (struct Node*) malloc(sizeof(struct Node) * stack.size);
    for(int i = 0; i < temp_stack.size; i++){
        stack.nodes[i] = temp_stack.nodes[i];
    }
    stack.nodes[stack.size - 1] = node;
}

Needless to say, this doesn't execute properly. 不用说,这不能正确执行。

The expected output would be: 预期的产出是:

Test
Test1

But, instead, I receive only ASCII-177. 但是,相反,我只收到ASCII-177。 It is also worth noting that the execution hangs after it prints that and moves to the new line. 值得注意的是,在打印并移动到新行之后执行挂起。 This results in Aborted (core dumped) . 这导致Aborted (core dumped)

Am I improperly freeing and re-allocating memory? 我不正当地释放并重新分配内存吗? Any help would be appreciated. 任何帮助,将不胜感激。 Thank you in advance! 先感谢您!

It's worth remembering that in C, passing a struct to a function is pass-by-value , ie, the function gets a copy of the struct. 值得记住的是,在C中,将结构传递给函数是按值传递 ,即函数获取结构的副本 All members of the struct, including pointer variables (but not whatever the pointer references), are duplicated. 结构的所有成员,包括指针变量(但不是指针引用)都是重复的。

So in the push function, think about what happens to the original when you modify this copy (eg, stack.size += 1 , and also when you free() the stack.nodes. 所以在push函数中,考虑修改此副本时原始文件会发生什么(例如, stack.size += 1 ,以及当你free() stack.nodes时。

Thank you to peekay for the recommendations. 谢谢你peekay的建议。 I ended up doing a re-write. 我最后做了重写。 It became quite a bit simpler. 它变得相当简单。 I did remove a layer of "visibility" by storing the nodes as a pointer, but I suppose this implementation is a bit more true to the data structure. 我确实通过将节点存储为指针来删除一层“可见性”,但我认为这种实现对数据结构更为真实。

Node is implemented as a means to hold data, and the user doesn't interact with it directly. 节点被实现为保存数据的手段,并且用户不直接与其交互。 It also points to the following Node. 它还指向以下节点。 Stack is implemented to hold the top Node, and also the size of the Stack. 实现堆栈以保存顶部节点,以及堆栈的大小。

Node: 节点:

struct Node{
    char val[MAX_DATA];
    struct Node *next;
};

Stack: 堆:

struct Stack{
    struct Node *top;
    int size;
};

Push: 推:

void push(struct Stack *stack, char *newVal)
{
    struct Node *newNode;
    newNode = (struct Node*) malloc(sizeof(struct Node));
    strcpy(newNode->val, newVal);
    newNode->next = stack->top;
    stack->top = newNode;
    stack->size++;
}

Usage: 用法:

struct Stack stack;
newStack(&stack);

push(&stack, "Test");
push(&stack, "Test1");
push(&stack, "Test2");
push(&stack, "Test3");

Complete Code 完整代码

Updated, accessible Nodes 更新的,可访问的节点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM