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

C语言按字符数从少到多排序字符串的代码问题求助

Fixing Your String Sorting Code & Implementing Required Functions

Hey there! Let's walk through why your code isn't running, fix those issues, then build the two functions you need (one using a 2D char array, another using a pointer array) as your task specifies.

Issues in Your Original Code

Your code has several key problems that prevent it from compiling/running correctly:

  • Wrong Array Type: You declared char words[100]; and char wordscopy[100]; as 1D arrays, but storing multiple strings requires a 2D char array (e.g., char words[100][STRSIZ]; where STRSIZ defines the max length per string). A 1D array can only hold one string, not a list.
  • Invalid scanf_s Usage: When reading into a 2D array's row, words[a] is already a pointer to the start of the string—you don't need &. Also, scanf_s requires a buffer size to avoid overflow: scanf_s("%s", words[a], STRSIZ);.
  • Broken String Copy: words[a] = wordscopy[a]; doesn't copy string content—it tries to assign pointers directly, which won't work. Use strcpy_s (or strcpy for non-MSVC compilers) to copy actual string data.
  • Type Mismatch in Swap: placeholder is a single char, but you're trying to swap entire strings. You need a temporary string buffer for swaps, or (for pointer arrays) swap the pointers themselves.
  • Syntax Error: Your final printf has an extra opening parenthesis before "Least Letters to Most Letters", causing a compile failure.
  • Missing Headers: You didn't include <stdio.h> (for I/O) or <string.h> (for strlen and string tools)—these are mandatory.

Fixed Version of Your Original Code

Here's a working version that matches your expected output:

#include <stdio.h>
#include <string.h>

#define STRSIZ 20  // Max length per string

int main() {
    int number;
    int a, b;
    char placeholder[STRSIZ];  // Temporary buffer for string swaps
    char words[100][STRSIZ];   // 2D array for original strings
    char wordscopy[100][STRSIZ];  // 2D array for sorted strings

    printf("Enter the amount of words or names you wish to sort (0 - 100) :\n");
    scanf_s("%d", &number);

    // Clear input buffer after reading the number
    while (getchar() != '\n');

    printf("Enter names or words on separate lines\n");
    for (a = 0; a < number; ++a) {
        scanf_s("%s", words[a], STRSIZ);
        // Copy original string to sorted array
        strcpy_s(wordscopy[a], STRSIZ, words[a]);
    }

    // Sort by string length (shortest to longest)
    for (a = 0; a < number; ++a) {
        for (b = a + 1; b < number; ++b) {
            // Swap if current string is longer than the next
            if (strlen(wordscopy[a]) > strlen(wordscopy[b])) {
                strcpy_s(placeholder, STRSIZ, wordscopy[a]);
                strcpy_s(wordscopy[a], STRSIZ, wordscopy[b]);
                strcpy_s(wordscopy[b], STRSIZ, placeholder);
            }
        }
    }

    // Print results with correct formatting
    printf("\n\n%-30s%5s%-30s\n\n", "Original Order", "", "Least Letters to Most Letters");
    for (a = 0; a < number; ++a) {
        printf("%-30s%5s%-30s\n", words[a], "", wordscopy[a]);
    }
    printf("\n\n");

    return 0;
}

Implementing the Two Required Functions

Now let's build the functions your task asks for:

1. Function Using 2D Char Array

This function sorts a 2D char array in-place by string length (shortest to longest):

#include <stdio.h>
#include <string.h>

#define STRSIZ 20

// Sorts a 2D char array by string length (shortest to longest)
void sort_strings_2d(char strs[][STRSIZ], int count) {
    int i, j;
    char temp[STRSIZ];

    for (i = 0; i < count - 1; ++i) {
        for (j = i + 1; j < count; ++j) {
            if (strlen(strs[i]) > strlen(strs[j])) {
                // Swap the two strings using a temporary buffer
                strcpy_s(temp, STRSIZ, strs[i]);
                strcpy_s(strs[i], STRSIZ, strs[j]);
                strcpy_s(strs[j], STRSIZ, temp);
            }
        }
    }
}

// Example usage
int main() {
    int num;
    char names[100][STRSIZ];

    printf("Enter number of names (0-100): ");
    scanf_s("%d", &num);
    while (getchar() != '\n');  // Clear input buffer

    printf("Enter %d names:\n", num);
    for (int i = 0; i < num; ++i) {
        scanf_s("%s", names[i], STRSIZ);
    }

    sort_strings_2d(names, num);

    printf("\nSorted by length (shortest to longest):\n");
    for (int i = 0; i < num; ++i) {
        printf("%s\n", names[i]);
    }

    return 0;
}

2. Function Using Pointer Array

This version is more efficient because it swaps pointers instead of copying entire strings:

#include <stdio.h>
#include <string.h>

#define STRSIZ 20

// Sorts a pointer array by string length (shortest to longest)
void sort_strings_ptr(char *strs[], int count) {
    int i, j;
    char *temp;

    for (i = 0; i < count - 1; ++i) {
        for (j = i + 1; j < count; ++j) {
            if (strlen(strs[i]) > strlen(strs[j])) {
                // Swap pointers (no need to copy string content!)
                temp = strs[i];
                strs[i] = strs[j];
                strs[j] = temp;
            }
        }
    }
}

// Example usage
int main() {
    int num;
    char names[100][STRSIZ];  // Stores actual string data
    char *name_ptrs[100];     // Pointer array pointing to each string

    printf("Enter number of names (0-100): ");
    scanf_s("%d", &num);
    while (getchar() != '\n');

    printf("Enter %d names:\n", num);
    for (int i = 0; i < num; ++i) {
        scanf_s("%s", names[i], STRSIZ);
        name_ptrs[i] = names[i];  // Assign pointer to each string
    }

    sort_strings_ptr(name_ptrs, num);

    printf("\nSorted by length (shortest to longest):\n");
    for (int i = 0; i < num; ++i) {
        printf("%s\n", name_ptrs[i]);
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者ayetman96

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:23:59