【发布时间】: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;
}
【问题讨论】:
-
您又忘记在
calloc失败时释放r... -
我告诉过你
sizeof(char)。您为什么不至少分析一下与原始版本的差异? -
我是编程新手,感谢您对我的耐心。我还没有深入讨论解除分配,这是我第一次尝试。
标签: c pointers multidimensional-array struct dynamic-data