C-在数组中计数分配的内存时出乎意料的输出



我正在研究一个动态分配项目,我会为测试用例提供一个不断的意外答案。输出始终打印出"大小测试:11",我不知道为什么。

getsize()如果不是null(实际上,计数数组中的所有有效元素),则填写所有值并添加到计数中。

我正在使用getsize()作为后备,而不是阵列列表中的var不能正确输出。另外,使用Calloc()创建的数组并引用了测试也很古怪。如果我要为循环打印所有值,它将在中途停止并崩溃(在尺寸25的数组中,它在索引7之后始终停止。,它可以很好地工作。逻辑是错误的,还是我必须冲洗某物?

如果我将测试用例更改为阵列的大小更大或更大,则在存在常数int打印的地方发生同一件事。

typedef struct ArrayList
{
    // We will store an array of strings (i.e., an array of char arrays)
    char **array;
    // Size of list (i.e., number of elements that have been added to the array)
int size;
    // Length of the array (i.e., the array's current maximum capacity)
    int capacity;
} ArrayList;
int main(void){
    struct ArrayList *test;
    test=createArrayList(25);
    int i=getSize(test);
    printf("test of size: %d", i);
    return 0;
}
//creates the array list and allocated memory for it
ArrayList *createArrayList(int length){
    struct ArrayList *r = malloc(sizeof(*r));
    if (r == NULL)//Returns null if malloc does not work
        return NULL;
    length=(length<DEFAULT_INIT_LEN) ? DEFAULT_INIT_LEN: length;//figures which value is         greater and keeps it
    r->array=calloc(sizeof(char), (length+1));
    if (r->array == NULL){//returns null if malloc does not work
            printf("errorn");
            return NULL;
    }
    r->size = 0;
    r->capacity = length;
    printf("Created new ArrayList of size %d.n", length);
    return r;
}
//the function im having trouble with
int getSize(ArrayList *list){
    int i=0, count=0;//index variables
    if (list->array==NULL)
        return -1;
    for (i=0; i<(list->capacity-1); i++){//goes through all indexs of internal array and     conuts valid elements. this is where im having trouble specifically
        if (list->array[i]!=NULL)
            count++;
    }
    return count;
}

这是错误的:

r->array=calloc(sizeof(char), (length+1));

应该是sizeof(char *),因为您正在为一系列指针分配空间。或者,更好的是,请勿将数组元素的类型进行编码,而是使用*r->array

r->array = calloc(sizeof(*r->array), length+1);

您分配length+1元素,然后仅在getSize()中升至capacity-1也有些奇怪。我认为您只想要length

在我看来,这部分试图索引列表元素:

for (i = 0; i < (list->capacity - 1); i++)
{
    if(list->array[i] != NULL)
        count++;
}

也许这对您要完成的工作更好:

while (list->array[i++] != NULL)
{
    count++;
}

最新更新