함수 내에서 동적 할당/rellocation는C - 나는 C에서이 기능을 작성했습니다
void add_to_str(char *character, char ** string, int* index)
{
//we dont expect *string to be NULL !! no condition done
if (*index == 0) //if str is empty we will alloc AVGLEN(32) characters space
*string=malloc(AVGLEN*sizeof(char));
if (*string == NULL) //malloc fails?
{
fprintf(stderr,errors[MALLOC]);
exit(99);
}
//string length exceeds 32 characters we will allocate more space
if (*index > (AVGLEN-1) || character== NULL)// or string buffering ended, we will free redundant space
{
*string=realloc(*string,sizeof(char)*((*index)+2));//+1 == '\0' & +1 bcs we index from 0
if (*string==NULL) //realloc fails?
{
fprintf(stderr,errors[REALLOC]);
exit(99);
}
}
*string[(*index)++]=*character;
}
(함수 포인터 뒤에 문자의 인덱스에 대한 포인터가 지정되면 (자),
char*
받을 필요 공간을 할당하고, 문자를 삽입한다)
언제 *index > 0
, 그것은 나에게 라인 세그먼트 오류를 제공
*string[(*index)++]=*character;
이 기능 (의 변형 char*
뒤에 바로 malloc
다음에 문자를 할당) 완벽하게 작동합니다.
평범하지 않은 표현을 자신의 문장으로 옮기는 것이 좋습니다. 컴파일러는 최적화 후에도 동일한 출력을 생성해야하며 예기치 않은 동작을 피하고 명확한 코드를 사용할 수 있습니다. – hyde