gpt4 book ai didi

c - 加倍动态堆栈数组

转载 作者:行者123 更新时间:2023-11-30 17:31:59 26 4
gpt4 key购买 nike

我有一个数组用于表示通用堆栈。

struct Stack {
int size;
int type;
int capacity;
void **data; // An array of generic data.
};

Stack *new_stack(int type) {
Stack *tmp = malloc(sizeof(Stack));
assert(tmp != NULL);
tmp->size = 0;
tmp->type = type;
tmp->capacity = DEFAULT_CAPACITY;
tmp->data = calloc(tmp->capacity, type);
assert(tmp->data != NULL);
return tmp;
}

这是在保留数据的同时将数组加倍的正确方法吗?

void realloc_stack(Stack *s) {
int old_capacity = s->capacity;
s->capacity *= 2;
s->data = realloc(s->data, s->capacity);
memset(s->data + old_capacity, 0, old_capacity);
assert(s->data != NULL);
}

但是,当我尝试像这样从 push_stack() 调用它时:

void push_stack (Stack *s, void *data) {
if (full_stack(s)) realloc_stack(s);
s->data[s->size++] = data;
}

我遇到了这个问题:基本上是一堆零,而实际数字应该是。

int main() {

Stack *intStack = new_stack(sizeof(int));

for (int i = 0; i < 15; ++i) {
push_stack(intStack, (void*)i);
}
}

结果:

Printing stack: 
14
13
12
11
10
0
0
0
0
9
8
7
6
1
0

最佳答案

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

#define DEFAULT_CAPACITY 8

typedef struct Stack {
int size; //number of element
size_t type; //size of type, there are no problems with int
int capacity;//max number of element
void *data; //memory of type * capacity
} Stack;

Stack *new_stack(size_t type) {
Stack *tmp = malloc(sizeof(Stack));
assert(tmp != NULL);
tmp->size = 0;
tmp->type = type;
tmp->capacity = DEFAULT_CAPACITY;
tmp->data = calloc(tmp->capacity, type);
assert(tmp->data != NULL);
return tmp;
}

void realloc_stack(Stack *s) {
int old_capacity = s->capacity * s->type;
s->capacity *= 2;
s->data = realloc(s->data, s->capacity * s->type);
assert(s->data != NULL);
memset((char*)s->data + old_capacity, 0, old_capacity);
}

static inline int full_stack(Stack *s){//Deleting a "static inline" if you are open to the public as an interface
return s->capacity == s->size;
}

void push_stack (Stack *s, void *data) {
if (full_stack(s)) realloc_stack(s);
memcpy((char*)s->data + s->type * s->size++, data, s->type);
}

void printIntObjectDump(Stack *s){
int i, *p = s->data;
for(i=0;i<s->capacity;++i){
printf("%d\n", p[i]);
}
}

int main() {
Stack *intStack = new_stack(sizeof(int));

for (int i = 0; i < 15; ++i) {
push_stack(intStack, &i);
}
printIntObjectDump(intStack);
return 0;
}

关于c - 加倍动态堆栈数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24394962/

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