为什么输出字符串以奇怪的方式连接?

时间:2016-08-01 11:46:08

标签: c string csv

我想使用我的通用向量来保存csv文件中一行的数据。但我遇到了一个问题。我的意见是:

  

MonsterID,名称,生命值,攻击,防御,AttackTimes,黄金,指数,特别

输出变为

Field 0 would be MonsterIName
Field 1 would be Name
Field 2 would be HitpointAttack
Field 3 would be Attack
Field 4 would be Defence
Field 5 would be AttackTiGold
Field 6 would be Gold
Field 7 would be Exp
Field 8 would be Special

以下是与此问题相关的代码部分:

Vector类型的定义:

typedef void (*VectorFreeFunction)(void *element);

typedef struct Vector {
    void *elements;   // An array of elements
    int capacity;     // The allocated size of the array
    int size;         // The number of elements in use
    size_t elemSize;  // Size of the data type of the element.
    VectorFreeFunction freeFunc;
} Vector;

csv.c

...
Vector *getfields(char *line) {
    int i = 0;
    const char *token;

    Vector *fields = vectorAlloc(sizeof(char*), NULL);

    for (token = strtok(line, ",");
         token && *token;
         token = strtok(NULL, ",\n"), i++)
    {
        vectorPush(fields, (const void*)token);
    }

    for (int i = 0; i != fields->size; i++) {
        printf("Field %d would be %s\n", i, (const char*)vectorAt(fields, i));
    }

    return fields;
}

vector.c

Vector *vectorAlloc(size_t elemSize, VectorFreeFunction freeFunc) {
    Vector *vector = malloc(sizeof(Vector));
    if (vector == NULL) {
        fatalError("Cannot allocate vector");
    }

    vector->capacity = DEFAULT_CAPACITY;
    vector->size = 0;
    vector->elemSize = elemSize;

    vector->elements = malloc(elemSize * vector->capacity);
    if (vector->elements == NULL) {
        fatalError("Cannot allocate elements array of the vector");
    }

    vector->freeFunc = freeFunc;
    return vector;
}

void *vectorAt(Vector *vector, int position) {
    assert(position < vector->size && position >= 0);
    return ((char*)vector->elements + (position * vector->elemSize));
}

void vectorPush(Vector *vector, const void *element) {

    if (vector->size == vector->capacity) {
        _vectorDoubleCapacity(vector);
    }

    void *destAddr = (char*)vector->elements + vector->size * vector->elemSize;
    memcpy(destAddr, element, vector->elemSize); // add to end of vector

    vector->size++;
}

void _vectorDoubleCapacity(Vector *vector) {
    vector->capacity *= 2;

    vector->elements = realloc(vector->elements, vector->elemSize * vector->capacity);
    if (vector->elements == NULL) {
        fatalError("Resizing the capacity of vector fails");
    }
}

1 个答案:

答案 0 :(得分:1)

您推送到Private Sub Button_Click_1(sender As Object, e As Windows.RoutedEventArgs) cmTabs.StaysOpen = True cmTabs.IsOpen = True End Sub 的元素是指向Vector line参数指向的数组的指针。很难以这种方式跟踪getfields元素的生命周期,您应该使用Vector分配令牌的副本,并在创建时将strdup()作为free传递VectorFreeFunction

此外,Vector返回一个指向vector元素的指针,它本身就是vectorAt,你使用它打印char *内容的方式是不正确的:你应该强制转换它为Vector并取消引用它。

以下是更正后的版本:

(char **)