⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lib.c

📁 Thinking in C++ 2nd edition source code which are all the cores of the book Thinking in C++ second e
💻 C
字号:
/*: C04:Lib.c {O}
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
Implementation of example C library */
/* Declare structure and functions: */
#include "Lib.h"
/* Error testing macros: */
#include <assert.h>
/* Dynamic memory allocation functions: */
#include <stdlib.h>
#include <string.h> /* memcpy() */
#include <stdio.h>

void initialize(stash* S, int Size) {
  S->size = Size;
  S->quantity = 0;
  S->storage = 0;
  S->next = 0;
}

void cleanup(stash* S) {
  if(S->storage) {
   puts("freeing storage");
   free(S->storage);
  }
}

int add(stash* S, void* element) {
  /* enough space left? */
  if(S->next >= S->quantity)
    inflate(S, 100);
  /* Copy element into storage,
  starting at next empty space: */
  memcpy(&(S->storage[S->next * S->size]),
    element, S->size);
  S->next++;
  return(S->next - 1); /* Index number */
}

void* fetch(stash* S, int index) {
  if(index >= S->next || index < 0)
    return 0;  /* Not out of bounds? */
  /* Produce pointer to desired element: */
  return &(S->storage[index * S->size]);
}

int count(stash* S) {
  /* Number of elements in stash */
  return S->next;
}

void inflate(stash* S, int increase) {
  void* v =
    realloc(S->storage,
      (S->quantity + increase)
      * S->size);
  /* Was it successful? */
  assert(v != 0);
  S->storage = (unsigned char*)v;
  S->quantity += increase;
} /* ///:~ */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -