📜  对字符串的动态二维数组进行排序

📅  最后修改于: 2022-05-13 01:57:52.820000             🧑  作者: Mango

对字符串的动态二维数组进行排序

先决条件:如何在 C 中动态分配二维数组?

双指针:指向另一个指针的指针称为双指针。使用双指针'**'来表示。双指针也称为指针指针。

例子:

Input: Geeks, Gfg,  Placement, Sudo, Gate
Output: Gate, Geeks, Gfg, Placement, Sudo

这个想法是以二维数组的形式为字符串动态分配内存和值。然后使用 strcmp 和 strcpy函数应用冒泡排序。

以下是所需的实现:

// C program to sort an array of strings
#include 
#include 
#include 
  
// Function to sort the values
void sort(char** names, int n)
{
    int i, j;
  
    // Perform sort operation using bubble sort
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - i - 1; j++)
            if (strcmp(names[j], names[j + 1]) > 0) {
                char* temp;
                temp = (char*)calloc(30, sizeof(char));
                strcpy(temp, names[j]);
                strcpy(names[j], names[j + 1]);
                strcpy(names[j + 1], temp);
            }
}
  
// Driver code
int main()
{
    char** names;
    int n, i;
    printf("Enter the number of names to be printed: ");
    scanf("%d\n", &n);
  
    // allocating memory for 1st dimension
    names = (char**)calloc(n, sizeof(char*));
  
    for (i = 0; i < n; i++)
    // allocating memory for 2nd dimension
    {
        names[i] = (char*)calloc(30, sizeof(char));
        scanf("%s", names[i]);
    }
    sort(names, n);
  
    printf("\nArray after sorting:\n");
    for (i = 0; i < n; i++)
        printf("%s\n", names[i]);
  
    return 0;
}

输出: