*EDIT: I Deleted by mistake the remarks I wrote on that using short & char is kind of obsolete / not efficient in modern programming. this one is just for practice basic stuff.**
This program creates and prints the series of signed short values starting from their equivalent in the unsigned short "space/world" starting at value 0 .
**example : on a machine where short is 16 bit :
unsigned short : 0 1 2 .... 65535
=> signed short : 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;
There are some other cleanups needed.
The function signature should change from
short initArr (short *p, unsigned int n);
to
unsigned int initArr (short *p, unsigned int n);
The variable 'lastValSet' should change its type to unsigned int.
This comment is also confusing:
//Assumption : the value of n can be converted to
// short int (without over/under-flow)
It should be something like:
//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.