MST

星途 面试题库

面试题:C语言指针数组基础应用

假设有一个指针数组,其元素指向不同长度的字符串。请编写代码,实现对这些字符串按字典序进行排序,并输出排序后的结果。要求利用指针数组操作,不能使用C++的标准库函数(如string类相关函数)。
49.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>

// 比较两个字符串的函数
int compare(const char *a, const char *b) {
    while (*a && *b && *a == *b) {
        a++;
        b++;
    }
    return *a - *b;
}

// 交换两个指针的函数
void swap(char **a, char **b) {
    char *temp = *a;
    *a = *b;
    *b = temp;
}

// 冒泡排序函数
void bubbleSort(char **arr, int n) {
    int i, j;
    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - i - 1; j++) {
            if (compare(arr[j], arr[j + 1]) > 0) {
                swap(&arr[j], &arr[j + 1]);
            }
        }
    }
}

int main() {
    char *strings[] = {"banana", "apple", "cherry", "date"};
    int n = sizeof(strings) / sizeof(strings[0]);

    bubbleSort(strings, n);

    int i;
    for (i = 0; i < n; i++) {
        printf("%s\n", strings[i]);
    }

    return 0;
}