开发者

Problem in truncating c array

I declared an array and take input from user. Now i want to 开发者_Go百科check duplicate entries, they have to be deleted and memory should be freed. Is it possible to free memory.

freeing the unused memory and reducing the array size?

I entered [10,21,3,4,4,2,6,7,21,4,10].it should get truncated as [10,21,3,4,2,6,7] and array length should now be 7,and i don't want to use sorting.


In C, you cannot change the size of an array. If you use dynamically allocated memory (with malloc()), you can use realloc() to resize the memory region, or allocate a new region, copy the data into it and free the old one.

A solution that is often acceptable is to simply leave part of the array unused. This is done by recording how many entries are used in a separate integer variable.


Simple implementation:

  1. When you do find a duplicate entry, shuffle the array left to fill the gap (covering the duplicate).
  2. Use realloc to reduce your allocation.

Note that you simply can't delete an arbitrary memory location. If runtime for filling gaps is a problem, consider an alternate structure such as a linked list, which would allow removal from the middle.

Removing duplicate entries is another problem. The general case involves sorting. You may have a special case which allows for better behavior.


I declared an array of length 100 and took input from user

so you mean like this:

    int input[100];
/* - ask 100 input from user */

Is it possible to free memory

the answer is no because you statically allocate 100 integers.

If you want to be able to reduce memory then you should do something like this:

int *tempBuffer=malloc(100*sizeof(int)); /* dynamic allocation */

for(i=0;i<100;++i) scanf("%d",&tempBuffer[i]);/* - ask 100 input from user */

int uniqueN=10   /* - assume the first 10 entries are the unique entries */

int *realBuffer=malloc(uniqueN*sizeof(int)); /* - allocate new buffer just enough for the unique entries */

for(i=0;i<uniqueN;++i) realBuffer[i]=tempBuffer[i];  /* - copy the unique entries from input to the final buffer */

free(tempBuffer);  /* - tempBuffer is now unused, free it */

/* here we have realBuffer with just enough size, no unused memory */

Another solution is to realloc tempBuffer after arranging the first uniqueN entries to be the unique entries:

realloc(tempBuffer,uniqueN);

don't forget to check if malloc or realloc returns NULL


Arrays are not dynamic in C. That said, you can access entries beyond the last one (given that an array variable is essentially a pointer). However, this is not safe.

Also, you cannot delete "array entries". You can move the rest of the elements to occupy the respectively previous positions. However, you cannot actually delete the area occupied by the element since an array is a contiguous piece of memory.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜