的qsort()通过给它一个N个项,其中任何给定项目(n)的地址是可计算使用每个“项目”的基础地址+大小的线性列表唱歌。因此,简单的东西开始,通过简单的我的意思是指针的列表。首先,可以通过将拷贝简单地拼接到原始文件(理想情况下少于一个字符,但我不打算约一个字节)来模拟缓冲区的循环性。即
"qwer" ==> "qwerqwer"
这可以这样做:
char *buff = malloc(2 * blocksize);
memcpy(buff, to_sort, blocksize);
memcpy(buff+blocksize, to_sort, blocksize);
现在你有偏移0 ..(块大小-1),其每一个为字符的块大小,即可以相对于彼此进行比较,而不任何特殊的指针数学。
其次,建立指针列表实际上排序,在这种情况下,
char** ptrs = malloc(sizeof(char*) * blocksize);
for (i=0;i<blocksize;i++)
ptrs[i] = buff+i;
接下来,是比较两个“项目”的功能。我们通过地址传递给我们的项目是指向字符串的指针。再次,地址过去作为左侧和右侧的内存位置我们会发现两个char *。地址本身不字符*:
int block_compare(const void *left, const void *right)
{
// memcmp would work for most platforms, but not all, so...
return strncmp(*(char **)left, *(char **)right, blocksize);
}
最后,发送这对的qsort()作为这样的:
qsort(ptrs, blocksize, sizeof(char*), block_compare);
的最终输出将是指针的块大小长度列表插入到制造循环缓冲区,每个缓冲区都引用一个块大小的块。上述一切的全文如下:
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
size_t blocksize = 0;
int block_compare(const void *left, const void *right)
{
// memcmp would work for most platforms, but not all, so...
return strncmp(*(char **)left, *(char **)right, blocksize);
}
int main(int argc, char* argv[])
{
char to_sort[] = "qwer";
size_t i = 0;
// set blockize
blocksize = strlen(to_sort);
char *buff = malloc(2 * blocksize);
memcpy(buff, to_sort, blocksize);
memcpy(buff+blocksize, to_sort, blocksize);
char ** ptrs = malloc(blocksize * sizeof(char*));
for (i=0;i<blocksize;++i)
ptrs[i] = buff+i;
// now send the pointer list to qsort()
qsort(ptrs, blocksize, sizeof(*ptrs), block_compare);
// ptrs is sorted. do with it what you will.
for (i=0;i<blocksize;i++)
{
fwrite(ptrs[i], sizeof(char), blocksize, stdout);
fwrite("\n", sizeof(char), 1, stdout);
}
fflush(stdout);
free(ptrs);
free(buff);
return EXIT_SUCCESS;
}
使用 “QWER” 生产:
erqw
qwer
rqwe
werq
另一个样本,采用 “asubstantiallylongerstringtest”
allylongerstringtestasubstanti
antiallylongerstringtestasubst
asubstantiallylongerstringtest
bstantiallylongerstringtestasu
erstringtestasubstantiallylong
estasubstantiallylongerstringt
gerstringtestasubstantiallylon
gtestasubstantiallylongerstrin
iallylongerstringtestasubstant
ingtestasubstantiallylongerstr
llylongerstringtestasubstantia
longerstringtestasubstantially
lylongerstringtestasubstantial
ngerstringtestasubstantiallylo
ngtestasubstantiallylongerstri
ntiallylongerstringtestasubsta
ongerstringtestasubstantiallyl
ringtestasubstantiallylongerst
rstringtestasubstantiallylonge
stantiallylongerstringtestasub
stasubstantiallylongerstringte
stringtestasubstantiallylonger
substantiallylongerstringtesta
tantiallylongerstringtestasubs
tasubstantiallylongerstringtes
testasubstantiallylongerstring
tiallylongerstringtestasubstan
tringtestasubstantiallylongers
ubstantiallylongerstringtestas
ylongerstringtestasubstantiall
男人,我希望这是你正在寻找。 (噢)。
我很惊讶,当你尝试解引用'xi'和'yi'时,它不会崩溃;你在32位或64位机器上? –
'q'在'r'之前,所以你的例子中的结果应该是'(2,0,3,1)'。 –
@AdamRosenfield是的,这也让我感到惊讶。它按预期在我的(64位)盒子上坠毁。 –