因此,我试图弄清楚如何做一些不同的事情,而我与C的合作不多,因此,非常感谢您的帮助。
typedef int data_t;
typedef struct set {
data_t *array;
size_t capacity;
size_t size;
} set_t;
typedef data_t* set_i_t;
#define CLEAR -1
我已经使用malloc并分配内存的此方法工作:
int set_init( set_t *set, int capacity ){
set->array = (data_t*)malloc(capacity * sizeof(data_t));
if(set->array == NULL){
return 1;
}
else{
set->capacity = capacity;
set->size = 0;
return 0;
}
}
还有一种释放它的方法:
void set_free( set_t *set ){
free(set->array);
set->array = NULL;
set->capacity = set->size = 0;
}
我试图以一种单独的方法将集合中的所有值设置为-1(CLEAR)
void set_clear( set_t *set){
int i = 0;
for (i = 0; i < set->size; i++){
set->array = CLEAR;
}
set->size = 0;
}
返回集合的大小:
int set_size( set_t set ) {
return sizeof(set->array);
}
返回容量:
int set_capacity( set_t set ) {
int capacity = set->capacity;
return capacity;
}
然后打印设置:
void set_print( set_t set ) {
//Honestly don't feel like i'm ready for this one yet.
}
如果有人可以指导我完成其中的几个操作,或者在这些操作方式上给我一些帮助,那将是很棒的。谢谢你们!
最佳答案
好的资源是C dynamically growing array
1个
您可以阅读有关size_t的信息。 What is size_t in C?
typedef int data_t;
// Here you are redefining int to data_t this is then used in array.
typedef struct set {
data_t *array;
// The address on heap where the typedef data_t is stored
size_t capacity;
size_t size;
} set_t;
typedef data_t* set_i_t;
// not sure why this is here maybe you use somewhere else
#define CLEAR -1
2
set_free(set_t * set);在我看来很好。
set_init();是但没有
set_t set_init(int capacity) {
// create it here then return it.
set_t ret;
ret.array = (data_t*)malloc(capacity * sizeof(data_t));
if (ret.array == NULL) return NULL;
ret.capacity = capacity;
ret.size = 0;
return ret;
}
在调用功能
set_t A = set_init(5);
if (A == NULL) fprintf(stderr, "could not alloc memory\n");
// :)
3
void set_clear( set_t *set){
// you pass the address of the struct into the function. you could also use set_i_t
//int i = 0;
// why do this you can do it in the for loop as you can see
// for (i = 0; i < set->size; i++){
for (int i = 0; i < set->size; i++){
//set->array = CLEAR; common mistake
// you are saying the address of the array. aka array[0]
// this is the same as set->(array+i)
set->array[i] = CLEAR;
}
set->size = 0;
}
4和5
// looks good but again better ways of doing this.
set_size( set_t set );
set_capacity( set_t set );
更好的内存管理方式,例如此处的示例。 C dynamically growing array
6
阅读有关printf()的全部内容;
http://www.tutorialspoint.com/c_standard_library/c_function_printf.htm
void set_print( set_t set ) {
// Here you passed the struct in plain and simple no pointer......
// so you will use the '.' not the '->'
// Here we can take a look at printf();
// %d is used to print int variables.
// to start off you know you will have to loop through the array.
for (int i = 0; i < set.size; i++) {
// you know the array must be at least have one item in it.
printf("%d\n", set.array[i]);
// using printf print the data_t aka "int" item in the array
}
}
希望这可以帮助。 G