2017-04-08 16 views
0

* 편집 : 내가 실수로 짧은 메모를 사용하여 삭제했습니다. & char는 현대 프로그래밍에서 쓸모 없거나 효율적이지 않습니다. **모든 서명 된 짧은 숫자를 표시하는 프로그램

이 프로그램은 부호없는 짧은 "공백/세계"에서 값 0으로 시작하는 일련의 부호있는 short 값을 만들고 인쇄합니다.

** 예 :은 짧은 머신 16 비트 :
짧은 부호 0 1 2 65535 ....
=> 서명 단편 : 0 1 2 ... 32766 -32767 -32766 -32765 ... -2 -1

#include <stdio.h> 
#include <stdlib.h> 
#include <limits.h> 

//Initialize memory pointed by p with values 0 1 ... n 
//Assumption : the value of n can be converted to 
//    short int (without over/under-flow) 
unsigned int initArr (short int *p, unsigned int n); 

int main (void) 
{ 
    const unsigned int lastNumInSeq = USHRT_MAX; 
    short *p_arr = (short *) malloc ((lastNumInSeq + 1) * sizeof (short)); 
    short int lastValSet = initArr (p_arr, lastNumInSeq); //returns the "max" val written 

// for (unsigned i = 0; i < numOfElem; i++) 
//  printf ("[%d]=%d \n", i, (*(p_arr + i))); 

    printf ("lastValSet = %d *(p_arr + lastNumInSeq) = %d ", 
      lastValSet,*(p_arr + lastNumInSeq)); 

    return 0; 
} 

unsigned int initArr (short *p, unsigned int n) 
{ 
    unsigned int offset,index = 0; 

    while (index <= n){ 
     offset = index; 
     *(p + offset) = ++index -1 ; 
    } 

    return offset; 
+0

'* (P + 인덱스) = (-1 + (++ 인덱스)); // 이것이 강건한가? ': 이것은 UB이다. – BLUEPIXY

+1

"정의되지 않은 동작"... 읽을 대상 ... – Attie

+0

UB는 정의되지 않은 동작입니다. – BLUEPIXY

답변

0

다른 정리가 필요합니다.

함수 서명

short initArr (short *p, unsigned int n); 

에서

unsigned int initArr (short *p, unsigned int n); 

변수로 변경한다 'lastValSet'부호 INT로 그 종류를 변경한다.

이 코멘트

도 혼란 :

//Assumption : the value of n can be converted to 
    //    short int (without over/under-flow) 

그것은해야 뭔가처럼 :

//Assumption : the value of n which is of type int can be converted to 
    //    short int (without over/under-flow) up to 32767 which is the 
    //    max value for a variable of short type.