c中的动态数组使用realloc() [英] Dynamic Array in c using realloc()

查看:102
本文介绍了c中的动态数组使用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 multiply sizeof(int), change to, say

data = (int*)realloc(arr,12*sizeof(int));



Please note: you must NOT free data after reallocating.



Is there a way i can "push" a new element to the dynamic array pls?


If you are not restricted to C, have a look at std::vector. It does internally most things, you have to do in C.


这篇关于c中的动态数组使用realloc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆