C 언어 포인터 전달

본문 @lonelyrains 출품, 전재 출처 를 밝 혀 주세요.  글 링크: http://blog.csdn.net/lonelyrains/article/details/6637999
오늘 Liux 의 다음 C 언어 가 시스템 시간 을 가 져 오 는 코드 를 찾 았 습 니 다.
time_t now = time(0);
struct tm *tnow = localtime(&now);
printf("%d-%d-%d %d:%d:%d
",1900+tnow->tm_year, tnow->tm_mon+1, tnow->tm_mday, tnow->tm_hour, tnow->tm_min, tnow->tm_sec);
먼저 두 번 째 줄 코드, gcc 컴 파일 러 는 tm * tnow 의 방식 으로 정의 할 수 없 으 며, struct 로 시작 해 야 합 니 다. 그렇지 않 으 면 알림 이 정의 되 지 않 습 니 다.g + + 는 가능 합 니 다.그리고 함수 로 포장 하고 싶 습 니 다. 나중에 사용 하기에 편리 합 니 다. 결 과 는:
void vGetTime(struct tm *tnow)
{
    time_t now = time(0);
    tnow = localtime(&now);
    printf("%d-%d-%d %d:%d:%d
",1900+tnow->tm_year, tnow->tm_mon+1, tnow->tm_mday, tnow->tm_hour, tnow->tm_min, tnow->tm_sec); } // , struct tm now , vGetTime(&now) 。
실제로 함수 로 포장 한 후 tnow 포인터 가 바 뀌 었 습 니 다. 호출 된 now 로 돌아 갈 때 주 소 를 바 꾸 었 습 니 다.이 기초 의 잘못 은 거의 한 시간 동안 찾 았 다.나중에 다음 과 같이 수정 합 니 다.
void vGetTime(struct tm *tnow)
{
    time_t now;
    struct tm *tmp;
    now = time(0);
    tmp = localtime(&now);
    tmp->tm_year += 1900;
    tmp->tm_mon  += 1;

    memcpy((void*)tnow,(const void *)tmp,sizeof(struct tm));
}
마지막 으로 포함 해 야 할 헤더 파일 은 stdio. h, time. h, string. h (string. h 는 memcpy 가 필요 합 니 다. 경 고 는 포함 되 지 않 지만 잘못 보고 하지 않 습 니 다)

좋은 웹페이지 즐겨찾기