2017-10-27 16 views
0

구조체의 배열을 만들려고하는데 처음부터 크기를 모르겠습니다. C90에서 double 포인터로 malloc을 사용하십시오.

struct MyStruct** thing; 
size_t thing_len = 0; 
thing = (struct MyStruct**) malloc(thing_len * sizeof(struct MyStruct*)); 
//... 
thing_len += 1 
thing = (struct MyStruct**) realloc(thing_len * sizeof(struct MyStruct*)); 

내가 thingMyStruct** 대신 유형 MyStruct*을 얻고 0x0을 포함 할

. 그러나 내가 할 때

struct MyStruct* thing; 
size_t thing_len = 0; 
thing = malloc(thing_len * sizeof(struct MyStruct)); 
//... 
thing_len += 1 
thing = realloc(thing_len * sizeof(struct MyStruct)); 

그것은 일한다!

변경 사항이 있는지는 잘 모르지만 나는 -ansi-pedantic 옵션을 사용하고 있습니다. 코드

realloc(thing_len * sizeof(struct MyStruct*)); 

에서

+0

는 [mcve] 입력하세요이다. – Mat

+3

[C에서 malloc() 및 family의 반환 값을 캐스팅하지 않는 이유에 대한이 토론을 참조하십시오.] (https://stackoverflow.com/q/605845/2173917) –

+0

사용 된 기능에 대한 문서. – alk

답변

4

은 함수에 대한 잘못된 호출입니다. [] 형식을 사용해야합니다. man page을 확인하십시오.]

realloc(<old pointer>, new size); 

oldPointer = realloc (oldPointer, newSize); 

같은 형식의 코드 매우 위험한 조각, 말했다. realloc()이 실패 할 경우 원래 포인터도 잃게됩니다 !! realloc()를 사용

소정 방법

tempPointer = realloc (oldPointer, newSize); //store the return 
if (tempPointer)        // is it success? 
{ 
     oldPointer = tempPointer;    // cool, put it back to the variable you want 
} 
      //--> here, whether or not realloc is success, you still got a _valid_ pointer. 
+0

많은 경우,'realloc()'이 실패하는 경우에 비참한 죽음을 피할 운명이 될 것입니다. 명시적인'if (! oldPointer) out_of_memory_error()'는 SIGSEGV로 죽어가는 것보다 낫지 만, 어쨌든 코드가 사라질 경우 이전 포인터의 복사본을 유지하는 것은 반드시 도움이되지는 않습니다. "malloc_or_die", "realloc_or_die"등의 표준 함수가 없기 때문에 오류 처리 코드가 중복 될 필요가 없기 때문에 너무 나쁩니다. – supercat