加倍动态堆栈阵列

时间:2014-06-24 19:41:16

标签: c arrays dynamic stack realloc

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

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

2 个答案:

答案 0 :(得分:1)

#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;
}

答案 1 :(得分:-1)

扩展Paul Roub在上述评论中所说的内容:

你正在呼叫memset(s->data + old_capacity, 0, old_capacity);你的目的是用0&#39;来写出数组的后半部分;然而,这不是正在发生的事情。根据{{​​3}},memset&#34;将ptr指向的内存块的第一个num bytes 设置为指定值。&#34;您正在尝试使用32位而不是8的整数填充数组。因此,您应该调整对此的调用:

memset(s->data + (old_capacity * s->type), 0, old_capacity * s->type);

应该工作并解决您的问题。祝你好运!

相关问题