在结构中打印动态分配数组时的未定义行为
undefined behaviour while printing dynamic allocated array within a struct
我假设有两种数据类型,其中包含一个动态分配的数组,以及两个变量 akt
和 max
,它们指示数组中最后一个元素的位置和数组分别。还应该编写两个函数,以便第一个向数组添加新元素,如果 space 不够,则将数组重新分配到双 space 中。第二个函数也将新元素插入到数组中,但它重新分配数组,使其大小仅增加一个 place.so 我的代码是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>
struct DynArray
{
int *p, max, akt = 0;
};
struct DynArrayMin
{
int *p, max, akt = 0;
};
void dyn_arr_add(struct DynArray* d, int x)
{
if ((d->akt)>(d->max) - 1)
{
d->p = (int*)realloc(d->p, (d->max) * 2);
d->max *= 2;
}
d->p[d->akt] = x;
d->akt++;
}
void dyn_arr_min_add (struct DynArrayMin* d, int x)
{
if ((d->akt)>(d->max) - 1)
{
d->p = (int*)realloc(d->p, (d->max) + 1);
d->max++;
}
d->p[d->akt] = x;
d->akt++;
}
void main()
{
DynArray d;
DynArrayMin e;
int n, l, x,aa=0;
scanf("%d", &n);
d.max = n;
d.p = (int*)malloc(sizeof(int)*n);
e.max = n;
e.p = (int*)malloc(sizeof(int)*n);
do{
printf("enter number\n");
scanf("%d", &x);
dyn_arr_add(&d, x);
dyn_arr_min_add(&e, x);
aa++;
printf("want to enter another number; 0=no\n");
scanf("%d", &l);
} while (l != 0);
for (int i = 0; i < aa;i++)
printf("%d%d\n", d.p[i], e.p[i]);
free(e.p);
free(d.p);
system("pause");
return;
}
但是从 n
= 5 开始,这将是动态分配数组的初始大小,并将 1 到 8 之间的数字作为输入,我应该有这样的输出:
11
22
33
44
55
66
77
88
但我得到的是这个弹出消息 this pop-up message,以及在弹出消息中单击 "continue" 后的以下输出:
11
2-842203134
-33751037-33686019
-1414791683-1414812757
-1414812757-1414812757
66
77
88
你 malloc
个整数,但 realloc
个字节。
第一次调用 realloc
会使缓冲区变小,而不是变大。
我假设有两种数据类型,其中包含一个动态分配的数组,以及两个变量 akt
和 max
,它们指示数组中最后一个元素的位置和数组分别。还应该编写两个函数,以便第一个向数组添加新元素,如果 space 不够,则将数组重新分配到双 space 中。第二个函数也将新元素插入到数组中,但它重新分配数组,使其大小仅增加一个 place.so 我的代码是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>
struct DynArray
{
int *p, max, akt = 0;
};
struct DynArrayMin
{
int *p, max, akt = 0;
};
void dyn_arr_add(struct DynArray* d, int x)
{
if ((d->akt)>(d->max) - 1)
{
d->p = (int*)realloc(d->p, (d->max) * 2);
d->max *= 2;
}
d->p[d->akt] = x;
d->akt++;
}
void dyn_arr_min_add (struct DynArrayMin* d, int x)
{
if ((d->akt)>(d->max) - 1)
{
d->p = (int*)realloc(d->p, (d->max) + 1);
d->max++;
}
d->p[d->akt] = x;
d->akt++;
}
void main()
{
DynArray d;
DynArrayMin e;
int n, l, x,aa=0;
scanf("%d", &n);
d.max = n;
d.p = (int*)malloc(sizeof(int)*n);
e.max = n;
e.p = (int*)malloc(sizeof(int)*n);
do{
printf("enter number\n");
scanf("%d", &x);
dyn_arr_add(&d, x);
dyn_arr_min_add(&e, x);
aa++;
printf("want to enter another number; 0=no\n");
scanf("%d", &l);
} while (l != 0);
for (int i = 0; i < aa;i++)
printf("%d%d\n", d.p[i], e.p[i]);
free(e.p);
free(d.p);
system("pause");
return;
}
但是从 n
= 5 开始,这将是动态分配数组的初始大小,并将 1 到 8 之间的数字作为输入,我应该有这样的输出:
11
22
33
44
55
66
77
88
但我得到的是这个弹出消息 this pop-up message,以及在弹出消息中单击 "continue" 后的以下输出:
11
2-842203134
-33751037-33686019
-1414791683-1414812757
-1414812757-1414812757
66
77
88
你 malloc
个整数,但 realloc
个字节。
第一次调用 realloc
会使缓冲区变小,而不是变大。