我面临返回类型的问题。我在下面的文章中实现了矢量,我想在结构中再添加一个字段。

http://www.happybearsoftware.com/implementing-a-dynamic-array.html

我将其添加如下:

typedef struct {
  int size;      // slots used so far
  int capacity;  // total available slots
  int *data;     // array of integers we're storing
  char* dvalue ;
} Vector;


这是头文件中的定义

char* vector_get(Vector *vector, int index);


这是vector.c中的代码

char* vector_get(Vector *vector, int index) {
  printf("Passed 1");
    if (index >= vector->size || index < 0) {
    printf("Index %d out of bounds for vector of size %d\n", index, vector->size);
    exit(1);
  }
 // it shows red underline but there is no compilation error but only run time.
    return vector->dvalue[index];
}


我正在使用Visual Studio 2012。

请为我做错的地方提供帮助,为什么我无法检索数据并且崩溃了。

请帮我。

谢谢

这是其他信息,我如何设置价值。我必须存储int和字符串值,然后再检索它们。

char* vector_get(Vector *vector, int index);

void vector_set(Vector *vector, int index, int value,char*  dvalue);

void vector_set(Vector *vector, int index, int value, char*   dvalue) {
  // zero fill the vector up to the desired index
  while (index >= vector->size) {
    vector_append(vector, 0);
  }

  // set the value at the desired index
  vector->data[index] = value;
  vector->dvalue[index] = dvalue;
}

char* vector_get(Vector *vector, int index) {
  printf("Passed 1");
    if (index >= vector->size || index < 0) {
    printf("Index %d out of bounds for vector of size %d\n", index, vector->size);
    exit(1);
  }

    return vector->dvalue[index]; // it shows red underline but there is no compilation error but only run time.
}

最佳答案

首先,您需要将dvalue的类型更改为char **

typedef struct {
  int size;      // slots used so far
  int capacity;  // total available slots
  int *data;     // array of integers we're storing
  char** dvalue; // <--- Notice the change here
} Vector;


然后,您需要以与为dvalue分配空间相同的方式为data分配空间。您没有在任何代码中显示此内容,但是大概您有以下内容:

vector->data = malloc(vector->capacity * sizeof(int));


因此,您还将需要以下内容:

vector->dvalue = malloc(vector->capacity * sizeof(char *));


最后,设置dvalue时,可能需要复制字符串,具体取决于传递给vector_set()的内容:

// Possibly wrong if dvalue is not persistent.
// vector->dvalue[index] = dvalue;

// Make allocated copy instead.  If you don't have strdup(), write it yourself.
vector->dvalue[index] = strdup(dvalue);

10-04 21:58