如何将按城市值排序的城市数组中的指针插入到城市数组中?

时间:2019-02-07 22:28:54

标签: c arrays pointers struct

我可以肯定我在insertTowns函数内部使用的指针语法不正确,因为当我尝试运行文件时,在取消注释该函数中涉及指针的行时,只会遇到分段错误。我知道我只是在逻辑上而不是在语法上正确设置了功能。我的insertTowns指针语法在做什么?

为简单起见,假设FILE * infile没有问题,并且已在单独的文件中正确分配了数组。同样,将长度初始化为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);
}

1 个答案:

答案 0 :(得分:1)

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]; 
}

如果 length arrs.towns 的条目数,则以j = (*length) - 1开头,以便j+1 == *length*arrs.towns[j + 1]访问具有未定义行为的数组。在arrs.cities[*length]中可能是相同的,总是复制同一城市似乎也很奇怪。

length 个元素的数组中,有效索引为0 .. length-1


警告

zipCode = malloc(sizeof(char) * 5)

允许存储最多4个字符的 zipcode ,以放置结尾的空字符(在法国,zipcode使用5个字符,对于您而言可能不是这种情况,但是您没有提供足够的信息让我们知道)


很难说更多,因为您不给Minimal, Complete, and Verifiable example