gpt4 book ai didi

c - 通用堆栈停止弹出值

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:20 25 4
gpt4 key购买 nike

我正在尝试构建一个通用堆栈,但我的 pop-method 似乎是错误的,因为它打印了从 100 到 1 和 1 的数字。如果我将 pop-method 更改为此解决方案:Generic Stacks in C它弹出到 64,然后只是 64 乘以 0。

结构:

typedef struct {
void *elems;
int elemSize;
int logLength;
int allocLength;
void (*freefn)(void*);
} genStack;

C 源文件:

#include "genstacklib.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

void GenStackNew(genStack *s, int elemSize, void(*freefn)(void *)) {
s->elemSize = elemSize;
s->elems = malloc(4 * s->elemSize);
if (s->elems == NULL) {
perror("\n\nError: ");
}
s->allocLength = 4 * s->elemSize;
s->logLength = 0;
s->freefn = freefn;
}

void GenStackDispose(genStack *s) {
if (s->elems == NULL) {
printf("\n\nStack is not initialized!\n\n");
return;
}
/*if (s->freefn != NULL) {
int n = 0;
while (s->logLength != 0) {
freefn(s->elems + n * s->elemSize);
n++;
}
}*/
free(s->elems);
}

bool GenStackEmpty(const genStack *s) {
if (s->logLength == 0) {
return true;
} else {
return false;
}
}

void GenStackPush(genStack *s, const void *elemAddr) {
if (s->elems == NULL) {
printf("\n\nStack not initialized!\n\n");
return;
}
if (s->allocLength == s->logLength * s->elemSize) {
s->allocLength = 2*s->allocLength;
s->elems = realloc(s->elems, s->allocLength*s->elemSize);
}
memcpy(s->elems+s->logLength*s->elemSize,elemAddr,s->elemSize);
s->logLength++;
}

void GenStackPop(genStack *s, void *elemAddr) {
void *source = s->elems + (s->logLength-1)*s->elemSize;
memcpy(elemAddr,source,s->elemSize);
memcpy(s->elems,source,s->elemSize);
s->logLength--;
//memcpy((char*)s->elems+(s->logLength-1)*s->elemSize,elemAddr,s->elemSize);
}

测试堆栈(应将数字从 0 插入 100,然后弹出):

int main(int argc, char *argv[]) {

int val;
genStack IntegerStack;

GenStackNew(&IntegerStack, sizeof(int), NULL);
for (val = 0; val < 100; val++) {
GenStackPush(&IntegerStack, &val);
printf("Pushed: %d\n",val);
}

while(!GenStackEmpty(&IntegerStack)){
GenStackPop(&IntegerStack, &val);
printf("Popped: %d\n",val);
}

GenStackDispose(&IntegerStack);
}

最佳答案

GenStackPop 函数中的第二个 memcpy 调用似乎是多余的,除了破坏第一个元素外什么都不做:

memcpy(s->elems,source,s->elemSize);

关于c - 通用堆栈停止弹出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40589885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com