【问题标题】:Unexpected output while counting allocated memory in an array计算数组中分配的内存时出现意外输出
【发布时间】:2014-02-02 19:15:39
【问题描述】:

我正在处理一个动态分配项目,并且我不断得到一个测试用例的意外答案。输出始终打印出“大小测试:11”,我不知道为什么。

getSize() 遍历所有值,如果它不为 NULL,则将其添加到计数中(实际上,计算数组中的所有有效元素)。

我使用 getSize() 作为后备,以防 ArrayList 大小中的 var 输出不正确。此外,使用 calloc() 创建并引用 test 的数组很古怪。如果我执行一个 for 循环来打印所有值,它会在中途停止并崩溃(在大小为 25 的数组的情况下,它始终在索引 7 之后停止。)但是,如果我 printf 索引 if seg 循环出错,它完美地工作。是逻辑错了,还是我要刷什么?

如果我将测试用例更改为数组大小更大或更大的地方,那么在打印出常量 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("error\n");
            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;
}

【问题讨论】:

标签: c pointers multidimensional-array struct dynamic-data


【解决方案1】:

这是错误的:

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

它应该是sizeof(char *),因为您正在为指向 char 的指针数组分配空间。或者,更好的是,根本不硬编码数组元素的类型,而是使用*r-&gt;array

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

你分配length+1元素然后在getSize()中只上capacity-1也感觉有点奇怪。我想你只是想要length

【讨论】:

  • 第一个好,第二个崩溃,因为r->array还没有分配,所以*r->array指向无处
  • @esskar:错了。 sizeof(*r-&gt;array) 在编译时评估;它仅用于推断类型。绝对有效。
  • 令人惊讶的是,像这样的小东西可以改变程序的整个功能。我想当一切都完美无缺时,它只会增加兴奋感。谢谢!
【解决方案2】:

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

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

也许这更适合您想要完成的工作:

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

【讨论】:

  • 如果我错了请纠正我,但 while 循环不会考虑非 NULL 元素不连续的情况?
  • @Hammad:你没看错。我很自然地认为他们是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多