Я объявил массив длиной 100 и принял данные от пользователя
, поэтому вы имеете в виду следующее:
int input[100];
/* - ask 100 input from user */
Возможно ли освободитьпамять
ответ - нет, потому что вы статически выделяете 100 целых чисел.
Если вы хотите уменьшить объем памяти, вам нужно сделать что-то вроде этого:
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 */
Другое решение состоит в том, чтобы realloc
tempBuffer
после того, как первые uniqueN
записи будут уникальными:
realloc(tempBuffer,uniqueN);
, не забудьте проверить, malloc
или realloc
возвращает NULL