我们被赋予了用 C 编写动态数据结构的任务。我对 C 语言仍然非常陌生,如果有人能给我一些关于我做错了什么/我做错了什么的指针(大声笑),我将不胜感激应该阅读更多。
这是我到目前为止所拥有的:
弹性阵列.h
#ifndef FLEXARRAY_H
#define FLEXARRAY_H
typedef struct flexarrayrec flexarray;
flexarray *flexarray_new();
extern void flexarray_add(flexarray *a, char item);
extern void flexarray_set(flexarray *a, char item, int index);
extern char flexarray_get(flexarray *a, int index);
extern void flexarray_trim(flexarray *a);
extern void flexarray_print(flexarray *a);
#endif /* FLEXARRAY_H */
flexarray.c
#include "flexarray.h"
#include "mylib.h"
#define DEFAULT_CAPACITY 10
typedef struct flexarray{
int size;
int capacity;
char *array;
};
flexarray *flexarray_new(){
flexarray a;
a->capacity = DEFAULT_CAPACITY;
a->size = 0;
a->array = (char*) erealloc (a ,a->capacity * sizeof(char));
return a;
}
void grow(flexarray a){
a->capacity = a->capacity * 2;
a->array = (int*) erealloc (a ,a->capacity * sizeof(int));
}
void flexarray_add(flexarray a, char item){
if(a->size == a->capacity) grow(a);
a->array[a->size - 1] = item;
a->size++;
}
void set(flexarray a, char c, int index){
if(index < 0 || index > a->size) return;
a->array[index] = c;
}
char get(flexarray a, int index){
if(index < 0 || index > a->size) return;
return a->array[index];
}
void flexarray_trim(flexarray a){
if(a->size == a->capacity) return;
a->capacity = a->size;
a->array = (char*) erealloc (a, a->capacity * sizeof(char));
}
void flexarray_print(flexarray a){
int i;
printf("[");
for(i = 0; i < a->size - 1; i++){
printf("%c,", a->array[i]);
}
printf("%c]\n", a->array[i + 1]);
}
谢谢
编辑当前编译日志:
flexarray.c:10:1: warning: useless storage class specifier in empty declaration [enabled by default]
flexarray.c: In function 'flexarray_new':
flexarray.c:13:15: error: storage size of 'a' isn't known
flexarray.c: At top level:
flexarray.c:20:21: error: parameter 1 ('a') has incomplete type
flexarray.c:25:30: error: parameter 1 ('a') has incomplete type
flexarray.c:31:20: error: parameter 1 ('a') has incomplete type
make[2]: *** [build/Debug/MinGW_Actual-Windows/flexarray.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
BUILD FAILED (exit value 2, total time: 1s)