2012-10-07 3 views
1

나는 버퍼 (char *)를 통해 읽고 있는데, 나는 커서의 시작 위치를 추적하고 있는데, 버퍼에서 7-64 문자를 복사 할 수있는 방법이 있거나, 내 최선의 방법이다. poistion x에서 y 위치로 버퍼를 루프합니까? -char * 버퍼에서 y 위치의 x 문자를 읽는 방법?

int32_t size = this->getObjectSizeForMarker(cursor, length, buffer); 
cursor = cursor + 8; //advance cursor past marker and size 
char version[size] = this->getObjectForSizeAndCursor(size, cursor, buffer); 

:

대상 버퍼의 크기는 다른 함수의 결과가 동적이

variable-sized object 'version' may not be initialized

관련 코드 부분을 반환 초기화

을 계산 33,210

- 앞서 buffer 여섯 개 단위 포인터 (일곱 번째 인덱스에 도착하는)

int32_t FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) { 
    //skip the marker and read next 4 byes 
    cursor = cursor + 4; //skip marker and read 4 
    unsigned char *ptr = (unsigned char *)buffer + cursor; 
    int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; 
    return objSize; 

} 
+0

당신은 내가 멘토가 아닌 바로 그 것이다. –

답변

1

이동 한 다음 memcpy 64-7 (57) 바이트, 예를 들면 :

const char *buffer = "foo bar baz..."; 
char destination[SOME_MAX_LENGTH]; 
memcpy(destination, buffer + 6, 64-7); 

당신에게 destination 배열을 종료하여 표준 C 문자열 함수를 사용하여 작업 할 수 있습니다. 우리가 복사 된 57 바이트 후 인덱스의 null 문자를 추가하는 참고 :

/* terminate the destination string at the 58th byte, if desired */ 
destination[64-7] = '\0'; 

하는 동적 destination을 크기로 작업해야하는 경우, 배열 대신 포인터를 사용 : 당신이 C++에 있다면

const char *buffer = "foo bar baz..."; 
char *destination = NULL; 

/* note we do not multiply by sizeof(char), which is unnecessary */ 
/* we should cast the result, if we're in C++ */ 
destination = (char *) malloc(58); 

/* error checking */ 
if (!destination) { 
    fprintf(stderr, "ERROR: Could not allocate space for destination\n"); 
    return EXIT_FAILURE; 
} 

/* copy bytes and terminate */ 
memcpy(destination, buffer + 6, 57); 
*(destination + 57) = '\0'; 
... 

/* don't forget to free malloc'ed variables at the end of your program, to prevent memory leaks */ 
free(destination); 

솔직히, 당신이 정말로 아마 C++ strings librarystd::string 클래스를 사용한다. 그런 다음 string 인스턴스에서 substr 하위 문자열 메소드를 호출하여 관심있는 57 자 하위 문자열을 가져올 수 있습니다. 두통이 적고 휠을 다시 발명하는 일이 적습니다.

위의 코드는 C 및 C++ 응용 프로그램 모두에 유용합니다.

+0

잘 보입니다. 나는 이것을 밖으로 시험 할 것이다. –

+0

왜 내 커서에 의존하는 -7인지 궁금한가요? –

+0

'64-7'은 여러분이 복사하고있는 바이트 수를 보여줍니다. 이것을 57로 바꿀 수 있습니다. –

관련 문제