I have encountered a problem with the following function when I use it. I do not know what is going on, and would like to ask for advise. The program compiles without any error, but when I execute it, it just freezes and exits.
typedef long long unsigned int lluint;
typedef long long int llint;
typedef short unsigned int suint;
llint *genNumArray (const llint start, const llint end, const lluint byWhat){
llint diff = start < end ? start - end : (start == end ? 1 : end - start), *genList = calloc (diff, sizeof (llint));
for (llint i = 0;i != labs (diff) + 1;){
*(genList + i) = i * byWhat * (diff > 0 ? 1 : 0 - 1) + start;
if (start < end){
i++;
}else if (start > end){
i--;
}else {
break;
}
}
return genList;
free (genList);
}
The reason why I say this is strange is because if I change it a bit, it works perfectly. The change is this.
typedef long long unsigned int lluint;
typedef long long int llint;
typedef short unsigned int suint;
llint *genNumArray (const llint start, const llint end, const lluint byWhat){
llint diff = labs (start < end ? start - end : (start == end ? 1 : end - start)), *genList = calloc (diff, sizeof (llint));
for (llint i = 0;i != diff + 1;){
*(genList + i) = i * byWhat * (diff > 0 ? 1 : 0 - 1) + start;
if (start < end){
i++;
}else if (start > end){
i--;
}else {
break;
}
}
return genList;
free (genList);
}
This works however if I do this then "*(genList + i) = i * byWhat * (diff > 0 ? 1 : 0 - 1) + start;" will not work as well since diff will always be larger than 0. I have a hard coded solution for this problem, but will not use it unless it is absolutely necessary. My first question is, what is the real problem here, not the lines where it is, but the actual behavior of the compiler? And how would I be able to fix this without much change to the code? My version of mingw is 5.1.6. This is not a homework question, it is just a self project which is bothering me. And yes the header file above is in the same folder as my c file. Thank you for any help.
Oh yeah, sorry i forgot to show the c source of how I use the function. Here it is:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "myheader.h"
int main (){
llint *result = genNumArray (0, 100, 2);
for (lluint i = 0;i < 100 + 1;i++){
printf ("%3llu - %3llu\n", i, *(result + i));
}
return 0;
}