大大大大大大大大大大大大大大大 2024-08-24 16:43 采纳率: 33.3%
浏览 23
已结题

零基础200题编字典问题

零基础学C/C++188——编字典
注:需要用指针解决

img

img

img


本题摘自零基础200题我的编程之路
附网址:http://47.96.116.66/problem.php?cid=5103&pid=8

  • 写回答

21条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-08-25 00:51
    关注
    获得0.45元问题酬金
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX_WORD_LENGTH 100
    #define MAX_WORDS 100000
    
    // 函数原型
    int compareStrings(const char *str1, const char *str2);
    void swap(char **p1, char **p2);
    
    int main() {
        int n;
        scanf("%d", &n);
    
        if (n <= 0 || n > MAX_WORDS) {
            fprintf(stderr, "Invalid number of words.\n");
            return 1;
        }
    
        // 动态分配内存
        char **words = (char **)malloc(n * sizeof(char *));
        if (!words) {
            fprintf(stderr, "Memory allocation failed.\n");
            return 1;
        }
    
        // 读取单词并存储
        for (int i = 0; i < n; i++) {
            words[i] = (char *)malloc(MAX_WORD_LENGTH * sizeof(char));
            if (!words[i]) {
                fprintf(stderr, "Memory allocation failed.\n");
                return 1;
            }
            scanf("%s", words[i]);
        }
    
        // 冒泡排序
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (compareStrings(words[i], words[j]) > 0) {
                    swap(&words[i], &words[j]);
                }
            }
        }
    
        // 输出排序后的单词
        for (int i = 0; i < n; i++) {
            printf("%s\n", words[i]);
            free(words[i]);  // 释放内存
        }
    
        free(words);  // 释放内存
    
        return 0;
    }
    
    // 用于比较两个字符串的函数
    int compareStrings(const char *str1, const char *str2) {
        return strcmp(str1, str2);
    }
    
    // 用于交换两个字符串指针的函数
    void swap(char **p1, char **p2) {
        char *temp = *p1;
        *p1 = *p2;
        *p2 = temp;
    }
    
    
    评论

报告相同问题?

问题事件

  • 系统已结题 9月1日
  • 修改了问题 8月24日
  • 修改了问题 8月24日
  • 赞助了问题酬金15元 8月24日
  • 展开全部