簡體   English   中英

在 C 中打印排序數組時變得奇怪 output

[英]Getting strange output when printing sorted array in C

我正在開發一個程序,該程序從命令行獲取任意數量的 arguments,將它們切成兩半,將它們放入數組中,按字母順序對它們進行排序,然后按順序打印它們。 它最多可以工作三個 arguments,但之后會給出一些奇怪的 output。 Output這是我目前所擁有的:

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

struct string {
    char *first_half;
    char *second_half;
};

int cstring_cmp(const void *a, const void *b);
int arrayIndex = 0;

int main(int argc, char *argv[])
{
    int numArguments = argc; 
    char **new_array = malloc(argc * sizeof(char*));
    struct string word;

    for (int i = 1; i < argc; i++) 
    {
        int len = strlen(argv[i]);
        int len_first = len/2;
        int len_second = len - len_first;

        word.first_half = malloc( (len_first + 1) * sizeof(char) );
        word.second_half = malloc( (len_second + 1) * sizeof(char) );

        memcpy(word.first_half, argv[i], len_first);
        memcpy(word.second_half, argv[i]+len_first, len_second);

        new_array[arrayIndex] = word.first_half;
        if(word.second_half != " ")
            new_array[arrayIndex+1] = word.second_half;

        arrayIndex += 2;

        //free(word.first_half);
        //free(word.second_half);
    }

    qsort(new_array, ((argc - 1)*2), sizeof(char *), cstring_cmp);

    for (int i = 0; i < ((argc - 1)*2); ++i)
    {
        printf("%s\n", new_array[i]);
    }

  return 0;
}

int cstring_cmp(const void *a, const void *b) 
{ 
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
} 

您沒有將word.first_halfword.second_half的最后一個字符設置為'\0' 因此,比較 function 將在調用strcmp中具有未定義的行為, printf也是如此,因為它們都期望指向以空結尾的字符串的指針。

此外,您沒有為new_array分配足夠的空間。 它必須包含兩次argc-1元素。

if(word.second_half != " ")如果不觸發也會導致問題,因為您將 position 留在new_array中,該數組將被未初始化填充,因此上述函數將獲得無效指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM