2017-04-08 8 views
0

*編集:私は間違って削除しました。これは短くて& charを使って書きました。現代プログラミングでは効率的ではありません。 **すべての署名付きショートナンバーを表示するプログラム

このプログラムは、値0から始まる符号なし短い "space/world"に相当するものから始まる一連の符号付きshort値を作成して出力します。

**例:短マシン上の16ビット:
unsigned short型: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' unsigned 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. 
関連する問題