简体   繁体   English

C realloc(动态数组)-访问冲突

[英]C realloc (dynamic arrays) - Access Violation

Starting out with dynamic arrays in C. I am getting an access violation when in the insertArray function (either in the realloc line or when trying to store the element (char) in the array. 从C中的动态数组开始。在insertArray函数中(在realloc行中或尝试将元素(char)存储在数组中时),我遇到访问冲突。

Can't seem to work around it or get to the bottom of it. 似乎无法解决它或触及它的底部。 Thanks 谢谢

Code: 码:

#include <stdio.h>

typedef struct {
    char *array;
    size_t used;
    size_t size;
} Array;

Array elements;

void initArray(Array *a, size_t initialSize) {
    a->array = (char *)malloc(initialSize * sizeof(char));
    a->used = 0;
    a->size = initialSize;
}

void insertArray(Array *a, char element) {
    if (a->used == a->size) {
        a->size *= 2;
        a->array = (char *)realloc(a->array, a->size * sizeof(char));
    }
    a->array[a->used++] = element;
}

void popArray(Array *a) {
    a->used--;
}

void freeArray(Array *a) {
    free(a->array);
    a->array = NULL;
    a->used = a->size = 0;
}

char vars[15];

int main() {
    initArray(&elements, 2);
    printf("Enter 15 character String: ");
    scanf_s("%s", vars, 15);
    for (int i = 0; i < 15; i++) {
        insertArray(&elements, vars[i]);
    }
    freeArray(&elements);
}

I suspect the problem is caused by the missing #include <stdlib.h> . 我怀疑问题是由缺少的#include <stdlib.h>引起的。

See Do I cast the result of malloc? 请参见是否强制转换malloc的结果? to understand why you should not cast the return value of malloc . 了解为什么不应该malloc的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM