c - 如何按城镇值的排序顺序将指向城市数组的指针插入城镇数组?
问题描述
我确定我在 insertTowns 函数中错误地使用了指针语法,因为当我尝试运行我的文件时,当我取消注释该函数中涉及指针的行时,我会遇到分段错误。我知道我在逻辑上设置了正确的功能,而不是在语法上。我在 insertTowns 的指针语法中做错了什么?
为简单起见,假设 FILE * infile 没有任何问题,并且数组已在单独的文件中正确地 malloc'd。此外,长度被初始化为 0,然后在另一个 .c 文件中从 main 传递到 readFile 函数。所以这不是数组越界问题。
我看过很多关于指针的 youtube 视频(thenewboston 有一些很好的视频),查看了http://cslibrary.stanford.edu/106/和其他一些资源。
我在下面提供了我的代码片段而不是整个程序来保持简单,因为它只是一个语法问题:
typedef struct cityStruct { unsigned int zip; char * town; } city;
typedef struct zipTownsStruct {
int * zips; // indexs to main array cities sorted by zip
city * * towns; // pointers to main array cities sorted by town name
city * cities; // main array of cities in order from file not sorted
} zipTowns;
extern void insertTowns(zipTowns arrs, int * length) {
int j = (*length) - 1;
while (j >= 0 && ((strcmp(arrs.towns[j]->town, arrs.cities[*length].town)) > 0)) {
*arrs.towns[j + 1] = *arrs.towns[j];
j--;
}
*arrs.towns[j + 1] = arrs.cities[*length];
}
extern void readFile(zipTowns arrs, FILE * infile, int * length) {
char * zipCode;
char * town;
if((zipCode = malloc(sizeof(char) * 6)) == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
if((town = malloc(sizeof(char) * 26)) == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
while(fscanf(infile,"%s %s", zipCode, town) == 2) {
arrs.cities[*length].zip = atoi(zipCode);
arrs.cities[*length].town = town;
insertZips(arrs, length);
insertTowns(arrs, length);
(*length)++;
}
free(zipCode);
free(town);
}
解决方案
在
extern void insertTowns(zipTowns arrs, int * length) {
int j = (*length) - 1;
while (j >= 0 && ((strcmp(arrs.towns[j]->town, arrs.cities[*length].town)) > 0)) {
*arrs.towns[j + 1] = *arrs.towns[j];
j--;
}
*arrs.towns[j + 1] = arrs.cities[*length];
}
如果长度是您开始的arrs.towns的条目数,j = (*length) - 1
则以未定义的行为访问数组。大概同在,总是复制同一个城市似乎也很奇怪。j+1 == *length
*arrs.towns[j + 1]
arrs.cities[*length]
在长度元素数组中,有效索引是0 .. length-1
警告
zipCode = malloc(sizeof(char) * 5)
允许存储最多 4 个字符的邮政编码以有结束空字符的位置(在法国邮政编码使用 5 个字符,您可能不是这种情况,但您没有提供足够的信息让我们知道)
很难说更多,因为您没有给出Minimal, Complete, and Verifiable example
推荐阅读
- python - 熊猫选择根数为 3 次的行
- macos - Wireshark v3.05 在 macOS Catalina (10.15) 下崩溃:QT 库不兼容?
- django - 我应该为我的项目使用 Instagram postgressql id 生成器技术吗
- reactjs - 当我在视图中添加两张幻灯片时,React-slick 在 DOM 中显示 5 个幻灯片元素
- python-3.x - 将子列表中的行附加到新列表
- delphi - 有没有办法让 Delphi VCL Form 边框变圆?
- saxon - 如何获取发生 Saxon XSLT 编译错误的行号?
- excel - 选择一列多个csv文件,并以可识别的顺序合并到一个文件中
- java - Socket.io 突然崩溃,说“java.lang.IllegalArgumentException:需要包含原因的代码”。
- regex - 正则表达式 - 使用“替换”使用捕获组删除内容