同时添加超过13个元素,结果似乎不正确! 我的代码如下!添加12个元素时,结果为
NO.0为0
NO.1是1
NO.2是2
NO.3是3
NO.4是4
NO.5是5
NO.6是6
NO.7是7
NO.8是8
NO.9是9 NO.10是10
NO.11是11
当再添加一个时,结果会发生很大变化,我不知道这里发生了什么:
NO.0为0
NO.1是1
NO.2是2
NO.3是3
NO.4是4
NO.5是5
NO.6是6
NO.7是7
NO.8是0
NO.9是1
NO.10是2
NO.11是3
NO.12是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]);
}
答案 0 :(得分:1)
如评论中所述,您正在滥用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++;
}
答案 1 :(得分:0)
realloc()
不正确,因为它使用旧的
长度值malloc()
和realloc()
项检查丢失(可以返回NULL
)realloc()
不需要复制这是我写的代码:
#include <stdio.h>
#include <stdlib.h>
#define INIT_LENGTH 3
typedef struct dynarray {
int size;
int length;
int *array;
} myarray;
myarray *create(void) {
myarray *da;
da = (myarray *)malloc(sizeof(myarray));
if (da != NULL)
{
da->size = 0;
da->length = INIT_LENGTH;
da->array = (int *)malloc(da->length * sizeof(int));
if (da->array == NULL) {
free(da);
da = NULL;
}
}
return da;
}
void add(myarray *da, int val) {
int size = da->size;
int length = da->length;
int *ra = da->array;
if (size == length) {
length *= 2;
ra = (int *)realloc(da->array, length * sizeof(int));
}
if (ra != NULL) {
da->array = ra;
da->length = length;
da->array[size] = val;
da->size++;
}
else {
puts("Warning: failed to realloc() extra space, array size unchanged");
}
}
int main() {
int i;
myarray *da = create();
if (da == NULL) {
puts("Initial alloc failure");
exit(1);
}
//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]);
}