l4.pdf

memmove

image.png

Comparison functions

用户的比较函数需要遵守的规则:
https://www.gnu.org/software/libc/manual/html_node/Comparison-Functions.html#Comparison-Functions

  1. int compare_doubles(const void *p, const void *q)
  2. {
  3. double first = *(const double *)p;
  4. double second = *(const double *)q;
  5. return (first > second) - (first < second);
  6. }

Comparing structs

image.png

  1. struct coord {
  2. int x, y;
  3. };
  4. struct coord origin; // struct on stack
  5. struct coord *p = malloc(sizeof(struct coord)); // struct in heap
  6. // (note: sizeof works correctly for structs)
  7. origin.x = 0; // access field from struct variable
  8. // these next 3 lines access field via struct pointer
  9. *p.x = 0; // WRONG! precedence applies . first then *
  10. (*p).x = 0; // OK: parens used to override precedence
  11. p->x = 0; // BEST: preferred way to access

gdb protip: printing arrays

image.png

// ints.c
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int cmp_int(const void *p, const void *q)
{
    int first = *(const int *)p;
    int second = *(const int *)q;
    return first - second;
}

int nobetter_cmp_int(const void *p, const void *q)
{
    long first = *(const int *)p;
    long second = *(const int *)q;
    return first - second;
}

int main(int argc, char *argv[])
{
    int nums[12];
    int count = sizeof(nums)/sizeof(nums[0]);

    nums[0] = INT_MAX;
    nums[1] = INT_MIN;
    srand(time(0));
    for (int i = 2; i < count; i++)
        nums[i] = 50 - (rand() % 100);

    qsort(nums, count, sizeof(int), nobetter_cmp_int);
    for (int i = 0; i < count; i++)
        printf(" %4d", nums[i]);
    printf("\n");    
    return 0;
}

image.png