이 프로그램의 출력은 무엇이며 OS로 반환하는 것은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/279837

  •  07-07-2019
  •  | 
  •  

문제

그것은 일종의 C 퍼즐입니다. 프로그램이 실행을 완료하는지, 그렇다면 실행하는 데 시간이 얼마나 걸리는지, OS로 반환되는지 알려야합니다.

static unsigned char buffer[256];

int main(void)
{
  unsigned char *p, *q;
  q = (p = buffer) + sizeof(buffer);
  while (q - p)
  {     
      p = buffer;
      while (!++*p++);
  }
  return p - q;
}

편집] 인터뷰 질문 태그를 제거했습니다. 왜냐하면 사람들이 반대하는 주요한 것 같습니다. 이것은 훌륭한 작은 퍼즐이지만 모두가 이미 지적했듯이 훌륭한 인터뷰 질문은 아닙니다.

도움이 되었습니까?

해결책

이것이 끔찍한 인터뷰 질문이라는 사실에도 불구하고 실제로는 매우 흥미 롭습니다.

static unsigned char buffer[256];

int main(void)
{
  unsigned char *p, *q;
  q = (p = buffer) + sizeof(buffer);
  /* This statement will set p to point to the beginning of buffer and will
     set q to point to one past the last element of buffer (this is legal) */
  while (q - p)
  /* q - p will start out being 256 and will decrease at an inversely 
     exponential rate: */
  {     
      p = buffer;
      while (!++*p++);
      /* This is where the interesting part comes in; the prefix increment,
         dereference, and logical negation operators all have the same
         precedence and are evaluated **right-to-left**.  The postfix
         operator has a higher precedence.  *p starts out at zero, is
         incremented to 1 by the prefix, and is negated by !.
         p is incremented by the postfix operator, the condition
         evaluates to false and the loop terminates with buffer[0] = 1.

         p is then set to point to buffer[0] again and the loop continues 
         until buffer[0] = 255.  This time, the loop succeeds when *p is
         incremented, becomes 0 and is negated.  This causes the loop to
         run again immediately after p is incremented to point to buffer[1],
         which is increased to 1.  The value 1 is of course negated,
         p is incremented which doesn't matter because the loop terminates
         and p is reset to point to buffer[0] again.

         This process will continue to increment buffer[0] every time,
         increasing buffer[1] every 256 runs.  After 256*255 runs,
         buffer[0] and buffer[1] will both be 255, the loop will succeed
         *twice* and buffer[2] will be incremented once, etc.

         The loop will terminate after about 256^256 runs when all the values
         in the buffer array are 255 allowing p to be incremented to the end
         of the array.  This will happen sometime after the universe ends,
         maybe a little sooner on the new Intels ;)
      */
  }
  return p - q;
  /* Returns 0 as p == q now */
}

본질적으로 이것은 256 자리의 기본 256 (8 비트 바이트) 카운터이며 전체 카운터가 "롤오버"되면 프로그램이 종료됩니다.

이것이 흥미로운 이유는 코드가 실제로 완전히 합법적이기 때문입니다 (이러한 유형의 질문에서 일반적으로 찾을 수있는 정의되지 않은 또는 구현 정의 된 동작이 없음). 실제로 약간 숨겨져 있음에도 불구하고 합법적 인 알고리즘 문제가 있기 때문입니다. 그것이 끔찍한 인터뷰 질문 인 이유는 아무도 언급 된 운영자의 우선 순위와 연관성을 기억하지 않기 때문입니다. 그러나 그것은 재미 있고 통찰력있는 작은 운동을 만듭니다.

다른 팁

이 코드는 쓰레기입니다. 의견을 참조하십시오

static unsigned char buffer[256];
int main(void)
{
  unsigned char *p, *q;
  q = (p = buffer) + sizeof(buffer);    //p=buffer, q=buffer+256
  while (q - p)    //q-p = 256 on first iteration
  {     
      p = buffer;        //p=buffer again
      while (!++*p++);   //increment the value pointed at by p+1 and check for !0
  }
  return p - q;    //will return zero if loop ever terminates
}

종료 될 수 있습니다. while 루프는 본질적으로 비 초기 버퍼를 스캔하므로 대신 액세스 위반을 던질 수 있습니다. 나는 ++*p ++의 바인딩 우선 순위를 기억하지 못하거나 그것을 찾을만큼 충분히 신경 쓰지 않습니다.

이것이 실제로 인터뷰 질문이라면, 내 대답은 "이것이 내가 당신과 함께 일할 것으로 기대하는 종류의 코드라면, 나는 직업을 원하지 않습니다"입니다.

편집 : Robert Gamble 덕분에 정적 배열이 자동으로 0으로 초기화되어 있으므로 코드는 완전한 쓰레기가 아니지만 여전히 관리하거나 쓴 Nutjob과 함께 작업하고 싶지는 않습니다.

이 질문에 대한 정답은 다음과 같습니다.

이 코드는 유지할 수없고 테스트가 어려우며 목적이 없으며 제거 또는 다시 작성해야합니다.

다른 것은 인터뷰 대상자가 소프트웨어 엔지니어로 생각하지 않는다는 것을 의미합니다.

다시 한 번, 엔지니어링 위치에 대한 인터뷰가 아닐 수도 있습니다.

unsigned char *p, *q;

이것은 많은 수준에서 마모되지 않습니까? 우선, 서명되지 않은 문자와 같은 것이 있습니까? 둘째, 나는 여기서 틀릴 수 있으므로 나를 인용하지 말고 char *p는 아닙니다. Q 펑키 결과를 생성합니까? 그건 또는 숯을 쉽게 할 수있게 해줍니다. P, Q는 나쁜 형태입니다.

다음이 훨씬 좋습니다.

char* p;
char* q;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top