2017-05-10 10 views
0

아래 코드의 출력이 -1과 -2 인 이유는 1과 2 여야합니다. 맞습니까?왜 아래 코드의 출력이 -1과 -2입니까?

또한 아래의 구조의 64 비트 서버 크기는 4 바이트입니다. 8 바이트가 적당합니까?

#include<stdio.h> 
struct st 
{ 
     int a:1; 
     int b:2; 
}; 
main() 
{ 
     struct st obj={1,2}; 
     printf("a = %d\nb = %d\n",obj.a,obj.b); 
     printf("Size of struct = %d\n",sizeof(obj)); 
} 
+0

당신은 대답을'-1 and -2' 또는'-1 and 2'로 받습니까? –

+0

@SouravGhosh -1 and -2 Sir – Chirag

+0

"1과 2이어야합니다, 맞습니까?" 아니, 왜 그런 식으로해야한다고 생각하니? – Gerhardh

답변

3
사용할 수있는 모든 경고와 함께

컴파일하고 컴파일러는 말씀을 읽어

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:7:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int] 
main() 
^ 
main.c:9:26: warning: implicit truncation from 'int' to bitfield changes value 
     from 2 to -2 [-Wbitfield-constant-conversion] 
     struct st obj={1,2}; 
         ^
main.c:11:40: warning: format specifies type 'int' but the argument has type 
     'unsigned long' [-Wformat] 
     printf("Size of struct = %d\n",sizeof(obj)); 
           ~~ ^~~~~~~~~~~ 
           %lu 
3 warnings generated. 

리콜,

이 서명 한 비트 변수가 두 값을 보유 할 수있는, -1 및 0

answer에서 볼 수 있습니다.

그래서 당신이 사용하는 경우이 대신 구조체 :

struct st 
{ 
     int a:2; 
     int b:3; 
}; 

당신이 원하는 출력을 얻을 것이다.


answer도 좋은 설명을 제공합니다.

+1

감사합니다 ......... – Chirag

+0

오신 것을 환영합니다 @Chirag, 작동 구조체로 나의 답변을 업데이트했습니다, 이것이 수용하기에 충분할 것입니다! :) – gsamaras

+0

예, 저는이 개념으로 매우 명확합니다. 도움에 감사드립니다. – Chirag