You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言字符串冒泡排序异常求助:城市排序故障排查

Fixing Your City Sorting Issue + String/Pointer Basics

Hey there! Let's work through your sorting problem and break down the key concepts you might be confused about—since you're new to C string/char operations, this will help you avoid similar issues down the line.

First, Let's Identify the Problems in Your sortCities Function

Your code has two main issues causing the broken sort output:

  1. Incorrect Swap Logic (Pointer vs. String Content)
    The strSorted array stores pointers to the individual city strings inside your strFunc buffer (created by strtok). When you use strcpy to swap the contents of these pointers, you're overwriting the actual characters in strFunc—which breaks the other pointers in the array (since they all point to the same buffer). Instead, you just need to swap the pointers themselves, not the string data they point to.

  2. Hardcoded Loop Counts
    You’re using fixed values (j<6, k<7) for your sorting loops. This only works if you always have exactly 7 cities. If your input string changes, this will cause out-of-bounds access or miss elements. Instead, use the actual count of cities you stored in i.

Fixed sortCities Function

Here’s the corrected version, with comments explaining each change:

void sortCities(const char strSehir[]) {
    char strFunc[100];
    // Store pointers to each city (no need for size 100, 10 is enough for your example)
    char *strSorted[10];
    int cityCount = 0;
    // Use a pointer for swapping, not a char array
    char *temp;

    strcpy(strFunc, strSehir);
    // Initialize first pointer
    strSorted[cityCount] = strtok(strFunc, " ");
    while (strSorted[cityCount] != NULL) {
        cityCount++;
        strSorted[cityCount] = strtok(NULL, " ");
    }

    // Use cityCount instead of hardcoded 7—since cityCount is 7 for your input
    for (int j = 0; j < cityCount - 1; j++) {
        for (int k = j + 1; k < cityCount; k++) {
            // Compare the strings via pointers, then swap the pointers
            if (strcmp(strSorted[j], strSorted[k]) > 0) {
                temp = strSorted[j];
                strSorted[j] = strSorted[k];
                strSorted[k] = temp;
            }
        }
    }

    printf("\nSorted cities:\n");
    for (int x = 0; x < cityCount; x++) {
        printf("%s ", strSorted[x]);
    }
    printf("\n");
}

Key Concepts to Remember

  • strtok Behavior: strtok modifies the input string by replacing delimiters with \0 characters. All pointers returned by strtok point to locations inside the original buffer (in your case, strFunc). That’s why swapping pointers is safe, but swapping string contents isn’t—it messes up the other pointers.
  • Pointer Arrays: When you have char *strSorted[], each element is a pointer to a string. Swapping these pointers just changes which string each index points to, without modifying the actual string data.
  • Avoid Hardcoding: Always use dynamic counts (like cityCount here) instead of fixed numbers. This makes your code flexible and less error-prone.

Quick Check for Your First Function (sortStartwB)

Your first function works, but a small improvement: initialize strBsehir properly (you have char strBsehir[50] = {}; which is good, but make sure you don’t exceed its size—your input is small, so it’s okay now). Also, you can use toupper(ptrSehir[0]) == 'B' to make the check case-insensitive if needed, but that’s optional.

内容的提问来源于stack exchange,提问作者Ertuğrul Gülümcan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:38:37