C中的动态数组向量

时间:2016-11-03 14:19:09

标签: c pointers vector dynamic-arrays

●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]);
}

3 个答案:

答案 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()