The program that I am working on takes a file and parses it line by line then changes each line into a uint32_t and adds it into an array. From there I am supposed to sort the array with qsort().
I wrote my program how I thought it should be but when I test the code out it is saying that all the new uint32_ts are the same value. Is this because of a mistake when I change the string into the uint32_t? Would it be better to use strtoul?
One last question, is the implementation of my qsort correct? (it compiles and says that it has sorted things but I’m not sure since my conversion to uint_32 is obviously not correct.
Anyways here is the code:
int main(int argc, char* argv[]){
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r"); // should check the result
char line[256];
uint32_t parArray[256];
int compar(const void *a, const void *b){
const unsigned long long *x = a, *y = b;
if(*x > *y)
return 1;
else
return(*x < *y) ? -1: 0;
}
int lineCounter = 0; // starts at 0 for the array
while(fgets(line, sizeof(line), file)){
// parse all info here
uint32_t t = (uint32_t) line;
// build the array
parArray[lineCounter]=t;
lineCounter++;
printf("Original: %s, Unsigned Int: %u\n", line,t);
}
qsort(&parArray[0],lineCounter+1,sizeof(uint32_t*),compar);
int i;
for(i=0;i<lineCounter;i++){
printf("%u\n",parArray[i]);
}
return 0;
}
You’re not parsing the lines as you read them. Casting
lineto auint32_tsimply takes the address of that array in memory. That explains why every line of the output is the same. You probably want to callstrtoul(line, NULL, 10)or similar instead.Also, your second parameter to
qsortis off by one.lineCounterhas the correct value at the time the loop terminates: the number of lines in the file. By adding one, you’re introducing undefined behavior by reading past the populated values in the array.