【发布时间】:2013-11-18 21:38:23
【问题描述】:
我被困在对指针数组进行排序时,无法弄清楚我做错了什么。 基本上,我必须读取文件并创建两个数组,一个是结构数组,另一个是指向这些结构的指针数组。然后我必须对两个数组进行排序,第一个是指针,然后是结构,以及时间需要多长时间(现在我不在乎时间)。 运行程序后,看起来 bubble_sort_ptr() 不对数组进行排序。所以,我认为要么我写了一个错误的函数,当我创建一个指针数组时,我在那里做错了。
#include
#include
#define MAX_SIZE 500 /* max size of the file in kB */
#define NUM_OF_FILES 10 /* number of file to read, and sort */
typedef struct file_txt /* structure to store file information */
{
char filename[10];
char buffer[MAX_SIZE * 8 * 1000]; /* Null terminated text from the file */
int size; /* size of the file */
} file_txt;
void bubble_sort(file_txt array[]);
void bubble_sort_ptr(file_txt **arr);
int main()
{
int i;
file_txt* files; /* an array to store file information */
file_txt* files_ptr[NUM_OF_FILES]; /* an array to store pointers to file information */
if((files = (file_txt*) malloc(sizeof(file_txt) * NUM_OF_FILES)) == NULL) /* allocate memory for files array */
{
printf("Error calling malloc\n");
exit(1);
}
for(i = 0; i arr[k+1].size) /* decreasing order */
{
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
}
void bubble_sort_ptr(file_txt **arr)
{
int i, j;
file_txt *temp;
//printf("Inside ptr sort\n");
for(i = 0; i (*arr)[j+1].size)
{
temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1) = temp;
}
}
}
}
如果有人能解释我做错了什么,我将不胜感激。
【问题讨论】:
-
您的代码有误吗?或错误 not 张贴 here ??
-
你知道
(*arr)[j].size和arr[j]->size的区别吗?如果你认为它们是同义词,那你就错了。后者取消引用指针数组中的第 j 个指针。您的代码根据指针数组中的 first 指针取消引用第 j 个 结构。 -
如果您要删除或修改已链接到的文件,它将不再与发布的问题相关,因此请发布您需要帮助的代码。
-
@WhozCraig 如果我只需要比较它们所指向的结构的大小,这有什么不同吗?
标签: c arrays sorting pointers struct