我正在尝试在 C++ 中按字母顺序对充满可变长度记录的缓冲区进行排序。我之前问过如何实现这一点,并被告知要对指向记录的指针数组进行排序。我设置了一个指针数组,但意识到每个指针都指向记录的开头,但无法知道记录何时停止。当我尝试打印出数组中每个指针所指向的记录时,因此,对于每个指针,我都会得到所有记录的整个缓冲区,从指向的那个开始。(例如,如果缓冲区包含“Helloworld”,并且每个字母都有一个指针,则打印指针数组将产生“Helloworldelloworldlloworldloworldoworldworldorldrldldd”。)显然,这不是我想要的;此外, qsort 似乎也没有在指针数组上工作。当我调试时,指针指向的内存空间似乎包含非常奇怪的字符,这些字符绝对不属于 ascii 字符集,也不包含在我的输入文件中。我很困扰。以下是我的代码;我怎么能做到这一点而不会得到我现在得到的奇怪结果?非常感谢,bsg。
int _tmain(int argc, _TCHAR* argv[])
{
//allocate memory for the buffer
buff = (unsigned char *) malloc(2048);
realbuff = (unsigned char *) malloc(NUM_RECORDS * RECORD_SIZE);
fp = fopen("postings0.txt", "r");
if(fp)
{
fread(buff, 1, 2048, fp);
/*for(int i=0; i <30; i++)
cout << buff[i] <<endl;*/
int y=0;
//create a pointer to an array of unsigned char pointers
unsigned char *pointerarray[NUM_RECORDS];
//point the first pointer in the pointer array to the first record in the buffer
pointerarray[0] = &buff[0];
int recordcounter = 1;
//iterate through each character in the buffer;
//if the character is a line feed (denoting a new record),
// point the next pointer in the pointer array to the next
//character in the buffer (that is, the start of the next record)
for(int i=0;i <2048; i++)
{
if(buff[i] == char(10))
{
pointerarray[recordcounter] = &buff[i+1];
recordcounter++;
}
}
//the actual qsort (NUM_RECORDS is a constant declared above; omitted here)
qsort(pointerarray, NUM_RECORDS, sizeof(char*), comparator);
}
else
cout << "sorry";
cout << sizeof(pointerarray)/sizeof(char*);
for(int k=0; k < sizeof(pointerarray)/sizeof(char*);k++)
{
cout << pointerarray[k];
}
int comparator(const void * elem1, const void * elem2)
{
//iterate through the length of the first string
while(*firstString != char(10))
{
return(strcmp(firstString, secondString));
firstString++;
secondString++;
/
}
return 0;
}