显示所有签名短号

时间:2017-04-08 17:35:03

标签: c ansi-c

*编辑:我错误地删除了我用短文和短文写的评论。 char在现代编程中有点过时/不高效。这个只是练习基本的东西。**

该程序创建并打印一系列已签名的短值,从无符号短"空间/世界"中的等价物开始。从值0开始。

**示例:在短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;

1 个答案:

答案 0 :(得分:0)

还需要一些其他的清理工作。

函数签名应该从

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

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

变量&#39; lastValSet&#39;应该将其类型更改为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.