2010-03-10 5 views
1

같음 모든 것은 mystruct입니다.크기는 몇 가지 이유를 들어 1

크기 1을 얻는 이유는 무엇일까요? 감사합니다.

// fragments of my code 
struct mystruct { 
    char *raw; 
    int count; 
}; 

struct counter { 
    int total; // = 30 
} 

static struct mystruct **proc() 
{ 
    int i = 0; 
    gchar *key,*val; 
    struct mystruct **a_struct; 
    struct counter c; 

    a_struct = (struct mystruct **)malloc(sizeof(struct mystruct *)*c.total); 
    while (table (&iter, (gpointer) &key, (gpointer) &val)) { 

     a_struct[i] = (struct mystruct *)malloc(sizeof(struct mystruct)); 
     a_struct[i]->raw = (char*)key; 
     a_struct[i++]->count = (int)val; 

    } 

    size_t l = sizeof(a_struct)/sizeof(struct mystruct*); 
    printf("%d",l); // outputs 1 
} 
+2

또한 size_t에 % d 형식 지정자 대신 % zu를 사용하십시오. –

+0

감사합니다. 문제가 해결되었습니다! – Josh

답변

9

몇 가지 문제가 있습니다. 먼저, 포인터의 크기가 될 sizeof(a_struct)을 취하고 있습니다 (그 이후로는 a_struct입니다). 그런 다음 다른 포인터의 크기로 나눕니다. 보장 된 1.

게다가, 당신은 왜 부서를하고 있습니까? 내가 생각하는 당신이 원하는 것은 :

size_t l = sizeof(struct mystruct); 

또는

size_t l = sizeof(**a_struct); 

편집 : 나는 지금 부문에 대한 이유를 생각

; 그 배열의 크기를 찾으려고합니다. 그게 작동하지 않을거야 - sizeof는 C에서 컴파일 타임에만 작동합니다 (코드에 적용되지 않는 C99의 특별한 예외가 있음). 따라서 동적 배열의 크기를 알 수 없습니다.

+1

"'sizeof'는 C에서 컴파일 할 때만 작동합니다 ..."C99에서는 sizeof 만 VLA와 함께 사용할 수 있기 때문에 C99에서는 정확하지 않습니다.이 경우 VLA는 런타임에 작동합니다. – AnT

+0

@AndreyT, 잘 부탁드립니다. 하지만 OP 코드의 동적 배열 - malloc 접근 방식에는 적용되지 않습니다. –

4

포인터의 크기로 포인터 크기를 나눕니다.

1

a_structstruct mystruct에 대한 이중 포인터입니다.
struct mystruct *struct mystruct에 대한 포인터입니다.

크기는 모두 같습니다.

은 당신이 두 개의 포인터의 크기를 복용하고 다른 하나를 분할하는이 size_t l = sizeof(struct mystruct);

1

,

size_t l = sizeof(a_struct)/sizeof(struct mystruct*); 

a_struct 그래서이

size_t l = sizeof(struct mystruct **)/sizeof(struct mystruct*); 
말과 동일 struct mystruct **a_struct로 선언 함

모든 포인터는 크기가 같기 때문에 **는 *와 크기가 같기 때문에 항상 1로 평가됩니다.

여기에 인쇄하려는 내용이 확실하지 않습니다. 크기는 a_struct입니까? 또는 전체 할당 크기? a_struct의 크기는 c.total이고 총 할당은 malloc에 ​​전달한 모든 값의 합계입니다.

관련 문제