문제

Original question

Can I use realloc() function like the following code:

int *ptr, i, num=5;

for (i=0; i<num; i++)
  void *nptr = realloc (ptr, (i+1) * sizeof(int) );
도움이 되었습니까?

해결책

no, you should initialize ptr at the beginning and then assign the new value

int *ptr = 0;

for (unsigned i=0; i<5; i++) {
  void *nptr = realloc (ptr, (i+1) * sizeof(int) );
  if (nptr) ptr = nptr;
  else abort();
}

Otherwise at the first call you could pass some random value to realloc. And the memory that you allocate in subsequent calls would simply be lost.

다른 팁

No, You should initialize pointer ptr and nptr with NULL. And declare nptr before for loop. your code should be like:

#include<stdio.h>
#include<stdlib.h>
void main()
{
        int *ptr=NULL, i, num=5;
        void *nptr=NULL;
        for (i=0; i<num; i++)
        {
                nptr = realloc (ptr, (i+1) * sizeof(int) );
                if (NULL != nptr)
                    ptr = nptr;
        }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top