Click here to Skip to main content
15,920,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 :)

C#
#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;
}
Posted


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.
 
Share this answer
 
Comments
Gilmore Sacco 2-Jun-13 6:52am    
Thanks alot dear sir. I have used vectors in c++, but for this task i am limited by Ansii C. Anyways thaks for the help =)
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.
 
Share this answer
 
Comments
Gilmore Sacco 2-Jun-13 5:19am    
Thanks Alot sir that worked. I that that since i was adding only ONE new element to the array by doing do, but surely i was not.
Is there a way i can "push" a new element to the dynamic array pls?
CPallini 2-Jun-13 12:18pm    
As suggested, if you can use C++ then have a look at std::vector (it provides all you need). If you stick to C then, even if you need to add just one element, a good stategy is to make room for more items (e.g. doubling the current size of the array) and keep track of remaining free space (because realloc is a rather 'expensive' call).
Gilmore Sacco 2-Jun-13 13:20pm    
I dont want to sound rude, but if you help me in this http://www.codeproject.com/Questions/601508/MoreplusissuespluswithplusDynamicplusArraysplusinp i would be very glad
CPallini 2-Jun-13 15:58pm    
Done.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900