gpt4 book ai didi

c - 通用堆栈实现中的空指针(纯 C)

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

我正在尝试用纯 C 语言创建一个通用堆栈,但我遇到了一些指针问题,但不知道问题出在哪里。

这是我遇到问题的结构和函数:

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

void GenStackPush(genStack *s, const void *elemAddr);
void GenStackPop(genStack *s, void *elemAddr);

这就是实现:

void GenStackPush(genStack *s, const void *elemAddr)
{
s->elems[s->logLength] = elemAddr;
s->logLength++;
}

void GenStackPop(genStack *s, void *elemAddr)
{
s->logLength--;
elemAddr = s->elems[s->logLength];
}

用法应该是这样的:

int val; 
genStack IntegerStack;
for (val = 0; val < 6; val++)
GenStackPush(&IntegerStack, &val);

GenStackPop(&IntegerStack, &val);
printf("Popped: %d\n",val);

这是我遇到的问题:

genstacklib.c: In function ‘GenStackPush’:
genstacklib.c:60:10: warning: dereferencing ‘void *’ pointer [enabled by default]
genstacklib.c:60:2: error: invalid use of void expression
genstacklib.c: In function ‘GenStackPop’:
genstacklib.c:72:23: warning: dereferencing ‘void *’ pointer [enabled by default]
genstacklib.c:72:13: error: void value not ignored as it ought to be

我已经尝试了多种方法来修复代码,但都没有奏效。谢谢。

============================================= ===========================

所以,伙计们,感谢您的帮助!现在可以编译了,但是我改了一个API,是我们教授给的。 “const”限定词也有问题,所以我删除了它们。不是我的代码是这样的:

genstacklib.h:

#ifndef GENSTACKLIB_H
#define GENSTACKLIB_H
#define GenStackInitialAlocationSize 4

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

void GenStackNew(genStack *s,int elemSize);
void GenStackDispose(genStack *s);
int GenStackEmpty(const genStack *s);
void GenStackPush(genStack *s, void *elemAddr);
void GenStackPop(genStack *s, void *elemAddr);

#endif

genstacklib.c:

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

void GenStackNew(genStack *s,int elemSize)
{
void** newElems;

/* Allocate a new array to hold the contents. */
newElems = (void**) malloc(elemSize * GenStackInitialAlocationSize);

if (newElems == NULL)
{
fprintf(stderr, "Error with allocating the stack.\n");
exit(1); /* Exit, returning error code. */
}
s->elems = newElems;
s->allocLength = GenStackInitialAlocationSize;
s->logLength = 0; /*is empty*/

}

void GenStackDispose(genStack *s)
{
s->allocLength = 0;
free(s->elems);
}

int GenStackEmpty(const genStack *s)
{
return s->logLength == 0;
}

void GenStackPush(genStack *s, void *elemAddr)
{
s->elems[s->logLength] = elemAddr;
s->logLength++;
}

void GenStackPop(genStack *s, void *elemAddr)
{
s->logLength--;
elemAddr = s->elems[s->logLength];
}

如果您有任何改进它的想法或有什么要说的,我会很高兴听到。 :D

最佳答案

您正在尝试取消引用 void 指针而不进行类型转换为导致问题的其他类型。

关于c - 通用堆栈实现中的空指针(纯 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10044184/

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