gpt4 book ai didi

c - 我的动态数组有问题

转载 作者:行者123 更新时间:2023-11-30 19:19:09 25 4
gpt4 key购买 nike

当添加超过13个元素时,结果似乎不正确!我的代码如下!当添加 12 个元素时,结果为

the NO.0 is 0
the NO.1 is 1
the NO.2 is 2
the NO.3 is 3
the NO.4 is 4
the NO.5 is 5
the NO.6 is 6
the NO.7 is 7
the NO.8 is 8
the NO.9 is 9
the NO.10 is 10
the NO.11 is 11

当再添加一个时,结果改变了很多,我不知道这里发生了什么:

the NO.0 is 0
the NO.1 is 1
the NO.2 is 2
the NO.3 is 3
the NO.4 is 4
the NO.5 is 5
the NO.6 is 6
the NO.7 is 7
the NO.8 is 0
the NO.9 is 1
the NO.10 is 2
the NO.11 is 3
the NO.12 is 12

#include<stdio.h>
#include<stdlib.h>

typedef struct dynarray myarray;
struct dynarray {
int size;
int length;
int *array;
};

myarray *create(void) {
/* TODO: define for arrays */
myarray *da;
da = malloc(sizeof(myarray));
da->size = 0;
da->length = 3;
da->array = (int *)malloc(da->length * sizeof(int));
return da;
}


void add(myarray *array, int val) {
int i;
int length = array->length;
int size = array->size;
int *temp;
//printf("da->size1 = %d\nda->length1 = %d\n",array->size,array->length);

if (size == length) {
temp = (int *)malloc(length * sizeof(int));
for (i = 0; i<size; i++) {
temp[i] = array->array[i];
printf("%d,", array->array[i]);
}


//printf("!@#$@#$=%d\n",array->length);

array->array = (int*)realloc(array->array, sizeof(int)*length);
for (i = 0; i<size; i++)
array->array[i] = temp[i];
array->length *= 2;
length *= 2;
}
if (size <length) {
array->array[size] = val;
printf("array[%d]====%d\n", size, array->array[size - 1]);
array->size++;
}
}


int main() {
int i;
myarray *da = create();
//printf("da->size = %d\nda->length = %d\n",da->size,da->length);

for (i = 0; i<12; i++)
add(da, i);
// printf("a->size = %d\nda->length = %d\n",da->size,da->length);
for (i = 0; i<12; i++)
printf("the NO.%i is %d\n", i, da->array[i]);
}

最佳答案

正如评论中所说,您滥用了 realloc 并且没有正确编辑长度。添加内容如下:

void add(myarray *array, int val){
int length = array->length;
int size = array->size;

if(size == length){
array->length *= 2;
array->array=(int*)realloc(array->array,sizeof(int)*length);
}
array->array[size] = val;
array->size++;
}

关于c - 我的动态数组有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com