In C, using qsort for dynamically allocated array
Hello. I am having some problems using qsort on arrays that I allocated dynamically in C.
I have a method which dynamically creates an array from a file strings cointained from a file that looks like this: Code:
void readinput(){ The mysortcmp method looks like this: Code:
int mysortcmp(a,b) However, if I did not dynamically allocate input, such that the readinput method is like this: Code:
void readinput(){ Should I A) Create my own sort algorithm? B) Use qsort properly for dynamically allocated arrays, if you could please show me how? C) Do something else? (And btw, on my Code:
fgets(buf,80,file); Thanks a lot. |
I didn't read all the code, but this is wrong:
Code:
char alow[strlen(a)]; |
I'm actually kind of surprised that this even compiles:
Code:
char alow[strlen(a)]; |
The C99 standard allows for dynamically sized arays in functions other than main() when the size of the array is dictated by an argument.
They are called variable-length arrays. That said, I'm not sure if they work in the context of using strlen(). |
Quote:
As a side note, I just tested it out in gcc/g++ and it seemed to work fine. However, it appears that VC++ .Net 2003 still reports a compiler error. I know that MS has made huge strides in improving ANSI compliance since VC++ 6.0, but evidently this is one area where it still is lacking. |
Quote:
Code:
char tmp[strlen(class_member)+1]; Code:
char * tmp = new char[strlen(class_member)+1]; EDIT: BTW I'm using VS.NET 2002, not 2003 or the newer 2005 beta. They might have fixed it in these versions. |
Let's say I fixed that using char * and then malloc on it, putting printf for a and b (and that is also before using alow and blow) still give me garbage strings. I was wondering if everything else is correct such that the only real problem is that the compiler I'm using does not support dynamically allocated arrays for qsort, or the arguments I used for qsort are incorrect?
|
I took a brief look at this for you, and after printing out memory addresses it appears that when you use the dynamic array method, qsort is actually sending you a char** to the sorting method. Try the following:
Code:
int mysortcmp(a,b) Code:
qsort(input,count,x,mysortcmp); input, input + x, input + x*2, .. input + x*(count-1) Those addresses themselves are just the address locations for another char* in the case where you are using dynamically allocated arrays. It looks like you probably already understand the fundamental difference between a char** and a char[][], but just in case... The char[][] is all going to be one contiguous block of memory, where as the char** is going to be a pointer to an array of pointers, and thus, the memory for all the underlying char data is not contiguous... |
All times are GMT -5. The time now is 02:33 PM. |