开发者

append to dynamically allocated array in c

开发者 https://www.devze.com 2023-01-23 02:12 出处:网络
I try realloc but it didn\'t work this is the code. thanks for your help trial = malloc (4 * sizeof(int));

I try realloc but it didn't work

this is the code. thanks for your help

trial = malloc (4 * sizeof(int));

trial[0] = 1; trial[1] = 4;trial[2] = 7;trial[3] = 11;

trial = (int*)realloc(trial, sizeof(int) * 5);
trial[sizeof(trial)-1] = 23;

int a;
for(a = 0; a < sizeof(trial); a++){
        printf("TRIAL %d \n", trial[a]);
}

And the output look like this

TRIAL 1 
TRIAL 4 
TRIAL 7 
TRIAL 23 

It should be

TRIAL 1 
TRIAL开发者_如何学运维 4 
TRIAL 7 
TRIAL 11
TRIAL 23 


The problem is that sizeof does not tell you how many elements are in the array; it tells you how much space the pointer (which points to the first element) takes up. So sizeof(trial) == sizeof(int*), and not the number of elements. You need to store the length separately.


sizeof will return sizeof(int *), which is the size of the pointer. You will have to keep track of the size of the pointer seperately.

Also, you should not return realloc() to the pointer you are reallocating. If realloc returns NULL, it will not modify the pointer and you will lose it. It is best to use a temporary pointer as follows:

int *p;
int *tmp;
/*...*/
tmp = realloc(p, NEW_SIZE);
if (tmp != NULL) p = tmp;
else { /*...*/ }


sizeof() on dynamically allocated memory only returns the size of the type, not the size of the block allocated. So sizeof(trial) in this case will return 4, the size of an int*.


sizeof(trial) == a constant (probably 4 or 8). It won't be the count of elements you allocated.

You need something like

int n = 100;
trial = realloc(trial, n*sizeof(*trial));

trial[n-1] = K;  // K is some number.


sizeof returns the size of the type, in this case the size of an int * which I assume is 4 bytes. So you are making the array size 5, but you are setting element (4 - 1) to 23. You'll need to keep track of the size of the array through a variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消