7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C]qsort()を使う

Last updated at Posted at 2014-02-23

APIを覚える練習.
空白の要素も入った配列を昇順にソートすると,
空白が先頭に来てしまう.

空白を比較対象に入たくない場合は,
配列の長さを指定してソートする.

qsort(table, 4, sizeof(table[0]), compare_char);
の4の部分が該当する.

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

int compare_char(const void* left, const void* right) {
	char *left_char = (char *)left;
	char *right_char = (char *)right;

	return strcmp( left_char, right_char );
}

int main() {

	int i=0;
	char table[10][20] = { 
		"123",
		"A0",
		"Z0",
		"9w3"
	};

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

	printf(" --- sort\n");
	
	qsort(table, 4, sizeof(table[0]), compare_char);
	
	for(i=0; i<10; i++) {
		printf("%d %s\n", i, table[i]);
	}
}

#ポインタの配列に対応したqsort() 2014-03-09追記
コメントのご指摘を受けて,呼び出し先の比較関数でオブジェクトの型情報を正確に受け取る様に修正しました.追加で,配列の終端をNULLで定義して文字配列の終端を検知できるようにコードを修正しました.

qsort-withPointer.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int compare_char(const void* left, const void* right) {

    const char *left_char = *(const char **)left;
    const char *right_char = *(const char **)right;

    return strcmp( left_char, right_char );
}

int main() {

    int i=0;
    // 配列中に文字列リテラルを配置するのと等価
    const char* s0 = "123";
    const char* s1 = "A0";
    const char* s2 = "Z0";
    const char* s3 = "9w3";

    // 配列の終端に番兵(NULL)を配置
    const char* table[] = {s0, s1, s2, s3, NULL};

    printf(" --- original\n");

    // table[]の要素を数える
    // 配列の終端を表すNULLを検出するまでカウンタをインクリメントする
    i=0;
    while(table[i]) {
        printf("%d %s\n", i, table[i]);
        i++;
    }

    printf(" --- sort\n");

    qsort(table, i, sizeof(*table), compare_char);

    i=0;
    while(table[i]) {
        printf("%d %s\n", i, table[i]);
        i++;
    }
}
7
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?