包含char *

时间:2017-06-16 12:44:09

标签: c qsort

table.h

#ifndef table_h
#define table_h   

//  The object:
typedef struct Pair
{
    char* name;
    int number;
} Pair;

int comp_pair(const void* lhs, const void* rhs)
{
    Pair* lp = (Pair*) lhs;
    Pair* rp = (Pair*) rhs;

    const char* ln = lp->name;
    const char* rn = rp->name;

    return strcmp(ln, rn);
}

// The array and associated functions:
size_t table_capacity;                                           
size_t table_size;                                               
Pair* table;            // <------ Global variables -------------------

Pair* create_table (size_t capacity)
{
    Pair* p = 0;
    p = (Pair*) malloc(sizeof(*p) * capacity);

    if (p == NULL && capacity > 0)
    {
        perror("create_table()::bad allocation!\n");
        exit(-1);
    }

    table_capacity = capacity;

    return p;
}    

void insert (Pair* table, const char* name, int number)
{
    Pair* p = (Pair*) malloc(sizeof(*p));

    if (p == NULL)
    {
        perror("insert::bad allocation!\n");
        exit(-1);
    }

    p->name = name;
    p->number = number;

    table[table_size++] = *p;
}

void print_table(Pair p[], size_t size)
{
    size_t i = 0;
    for (i; i < size; ++i)
    {
        printf("%s -> %d\n", p[i].name, p[i].number);
    }
}

#endif

main.c

#include <stdio.h>
#include <stdlib.h>     // qsort() 
#include <string.h>     // strcmp()
#include <stddef.h>     // size_t
#include "table.h"

int main()
{
    char* names [ ] = { "bla1", "bla2", "bla3", "bla4", "bla5"};
    int numbers [ ] = { 1, 2, 3, 4, 5 };
    size_t s = 5;
    size_t i = 0;

    table = create_table(s);

    for (i; i < s; ++i)
    {
        insert(table, names[i], numbers[i]);    
    }

    qsort(table, table_size, sizeof(Pair), comp_pair);

    print_table(table, table_size);
    getchar();

    free(table);
}

当我尝试使用qsort()时,(调试)上面的代码会产生以下错误:

  

Access violation reading location 0x65727541.

问题:

      
  1. 函数comp_pair()是否正确?
  2.   
  3. 我应该以qsort()中的第三个参数,当前sizeof(Pair)或实际比较类型的大小(即char *?
  4. )传递多大的大小

0 个答案:

没有答案