btbytes (owner)

Revisions

gist: 144720 Download_button fork
public
Description:
Notes from "The C Book"
Public Clone URL: git://gist.github.com/144720.git
Embed All Files: show embed
c_refresher_notes.markdown #

C Refresher Notes

Notes from The C Book.

Introduction

  • To use exit(), EXIT_SUCCESS and EXIT_FAILURE include stdlib.h.

Variables and Arithmetic

  • Include <stddef.h> to use wchar_t

Arrays and Pointers

  • Qualified types -- const and volatile.

    • int i; // ordinary int
    • const int ci = 1 ; // constant integer
    • const int *pci ; // pointer to a constant int
    • int *const cpi = &i; // constant pointer to an int
    • const int *const cpci = &ci; //constant pointer to a constant int
  • sizeof is implementation dependent. It will be either unsigned long or unsigned int.

    • Use size_t provided in the <stdlib.h> -- size_t sz; sz = sizeof(sz);
    • Cast the return value to unsigned long. -- (unsigned long)sz;.
  • Use stdlib.h to declare malloc correctly.
  • Fundamental unit of storage in C is char.
  • malloc returns a null pointer if it cannot allocate requested free space.
  • stdio.h contains defined constant NULL. alternatively, use 0 or (void *)0.
  • Pointers to functions -- int (*func)(int a, int b);
  • call the function with -- (*func)(1,2); or func(1,2);.
  • An incomplete type is one whose name and type are mostly known, but whose size isn't yet been determined.
  • A function is not an object.
  • To get an incomplete type:

    • declare an array omitting info about it's size -- int x[];
    • declare a struct or union but not defining it's contents.
  • Pointers void can be converted backwards and forwards with ptrs to any object or incomplete type.

  • An unqualified ptr may be converted to a qualified ptr. The reverse is not true.

Structures

  • struct wp_char wp_char; -- This defines a var called wp_char of type wp_char. This means tags have their own namespace and cannot collide with other names.

    struct wp_char{

    char wp_cval;
    short wp_font;
    short wp_psize;
    

    }

    struct wp_char v2;

  • Pointer to the structure -- struct wp_char *wp_p;

  • Access -- (*wp_p).wp_cval; (. has higher precedence than *, hence the parens).
  • Or wp_p->wp_cval.
    #include 
    #include 

    struct somestruct{
      int i;
    };

    main(){
      struct somestruct *ssp, s_item;
      const struct somestruct *cssp;

      s_item.i = 1;   /* fine */
      ssp = &s_item;
      ssp->i += 2;    /* fine */
      cssp = &s_item;
      cssp->i = 0;    /* not permitted - cssp points to const objects */

      exit(EXIT_SUCCESS);
    }

In the above code, cssp->i = 0; tries to assign value to a const object; gcc does not allow this behaviour. tcc does.

  • Storage Layout -- Addressing restrictions might create "holes" in the structures. Eg: char|(hole)|short|short because char occupies one byte and shorts are expected to start from even numbered addresses.