●int vectorInsert(Vector * array,int index,Data value);
我在做
如果可以根据给定的陈述进行纠正。
我用
来调用它Vector *vect = initVector();
Data data_array[20];
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i]);
}
答案 0 :(得分:1)
您的代码中存在一些错误,但最重要的一个是在initVector
函数中,您实际上需要为向量分配内存。
您还需要执行以下操作:
initVector
返回v
而不是v->data
或&v
vectorInsert
打印array->data[index].value
而不是array->data[index]
vectorInsert
成功返回1
,在您的分配中添加错误检查,并在内存错误时返回0
。除原始malloc之外的所有这些都是编译器返回的警告。
答案 1 :(得分:0)
在编译器中启用所有警告和调试信息(例如,使用gcc -Wall -g
编译)。然后它应警告你
Vector * initVector(){
Vector *v; /// UNINITALIZED
v->max_size=0;
v->current_size=0;
v->data = malloc(sizeof(int)*v->max_size);
return v->data;
// return (&v);
}
所以你有一个undefined behavior,那就是awfully bad。
(当然编译器会提供很多其他警告,你应该改进你的代码,直到你没有任何警告。然后你应该使用gdb
调试器) < / p>
您可能想了解flexible array members。
或许考虑至少:
Vector* createVector(int maxsize) {
if (maxsize<=0)
{ fprintf(stderr, "bad maxsize=%d\n", maxsize); exit(EXIT_FAILURE); };
Vector* v = malloc(sizeof(Vector));
if (!v) { perror("malloc Vector"); exit(EXIT_FAILURE); };
v->data = malloc(sizeof(Data)*maxsize);
if (!v->data) { perror("malloc data"); exit(EXIT_FAILURE); };
v->max_size = maxsize;
v->current_size = 0;
memset(v->data, 0, sizeof(Data)*maxsize);
return v;
}
答案 2 :(得分:0)
首先,根据您的规范,max_size
应该是无符号整数,因此我使用Vector
更改了size_t
以反映这一点。我还将相关格式说明符从%d
更改为%zu
以匹配此新类型。
您的initVector()
函数需要为Vector
分配内存,因此已添加。此外,此处不需要为Data
结构的动态数组分配内存,因此v->data
设置为NULL
。此函数还应该返回指向新分配的内存v的指针,而不是指向此.data
的{{1}}字段的指针,就像您最初的那样。
在Vector
函数中,您忽略了检查内存分配错误,因此我在尝试分配后添加了一个检查,如果出现错误则返回0。插入新的vectorInsert()
结构后,您的增量Data
检查错误。首先,您需要增加.current_size
。接下来,您需要向array->current_size <= index
添加一个,而不是将.current_size
设置为大于索引值的一个。此外,在此处打印插入的值时,您忘记访问.current_size
字段。我认为这可能是由于您用于传递给.value
的{{1}}结构的名称混乱。您调用此结构Data
,因此在上一行中我们有vectorInsert()
,您将结构value
指定给array->data[index] = value
。但是在调用value
时,您希望显示结构array->data[index]
所拥有的值。选择更好的名字总是一场胜利!最后,此函数在成功插入时返回1。
我添加到您的测试代码中以显示printf()
和value
的内容,并添加了vect
结构vect->data
,以测试插入任意索引
最后,您需要在所有这些之后释放内存分配,因此我添加了几个对Data
的调用。
以下是代码:
test_insert
以下是结果示例:
free()