C语言返回类型

时间:2014-11-27 00:07:28

标签: c visual-studio-2012

我面临着返回类型的问题。我使用下面的文章来实现向量,我想在结构中添加一个字段。

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和string值,然后检索它们。

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.
}

1 个答案:

答案 0 :(得分:1)

首先,您需要将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);