c中的动态数组使用realloc() [英] Dynamic Array in c using realloc()
问题描述
Hello Experts,
早上好。
我很难理解为什么输出的输出与实际输出不同。我期待数组与ealloc保持一致,只添加新部分,但由于某种原因,原始数据正在被操纵。如果你有5分钟的时间,请看看我的代码。
谢谢:)
#include< stdio.h>
#include< stdlib.h>
#include< string.h>
int main( void )
{
int * arr;
int * data;
short i = 0 ;
arr =(int *)malloc(10 * sizeof ( int ) );
for (i = 0 ; i< 10; i ++)
{
arr [i] = i;
}
for (i = 0 ; i< 10; i ++)
{
printf( \ n%d,arr [i]);
}
printf( \ n\\\
TESTING!跨度>);
data =(int *)realloc(arr, sizeof ( int ) );
数据[ 10 ] = 181 ;
arr = data;
免费(数据);
for (i = 0 ; i< 12; i ++)
{
printf( \ n%d,arr [i]) ;
}
免费(arr);
scanf( %d,& i);
return 0 ;
}
Quote:data =(int *)realloc(arr,sizeof(int));
检查以上行:数组中没有''new part'',因为你忘记了乘以sizeof(int)
,改为,说
data =(int *)realloc(arr,12 * sizeof (int));
请注意:您之后不得免费数据
重新分配。
有没有办法可以将新元素推到动态数组中?
如果您不限于C
,请查看std :: vector
。它在内部大多数事情,你必须在C。
Hello Experts,
Good morning.
I am having so trouble to understand why the expeted output is differening from the real output. I am expecting the array to remain the same with ealloc, only adding the new part, but for some reason, the original data is being manipulated. Please take a look at my code, if you have 5 minutes to spare.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void)
{
int *arr;
int *data;
short i = 0;
arr = (int*)malloc(10* sizeof(int));
for(i=0; i<10; i++)
{
arr[i]=i;
}
for(i=0; i<10; i++)
{
printf("\n%d", arr[i]);
}
printf("\n\nTESTING!");
data = (int*)realloc(arr,sizeof(int));
data[10] = 181;
arr = data;
free(data);
for(i=0; i<12; i++)
{
printf("\n%d", arr[i]);
}
free(arr);
scanf("%d", &i);
return 0;
}
Quote:data = (int*)realloc(arr,sizeof(int));
Check the above line: there is no ''new part'' in the array because you forgot to multiplysizeof(int)
, change to, say
data = (int*)realloc(arr,12*sizeof(int));
Please note: you must NOT freedata
after reallocating.
Is there a way i can "push" a new element to the dynamic array pls?
If you are not restricted toC
, have a look atstd::vector
. It does internally most things, you have to do in C.
这篇关于c中的动态数组使用realloc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!