C Cheat Sheet

Array initialization

int a[4] = {[2] = 6, [3] = 7};
int grid[100][100] = [0][0] = 8, [50][25] = 7};

Structure initialization

struct address {
                 int street_no;
                 char *street_name;
                 char *city;
                 char *prov;
                 char *postal_code;
struct address temp_address = { .city = "Hamilton", .prov = "Ontario" };

struct a {
         struct b {
              int c;
              int d;
          } e;
         float f;
} g = {.e.c = 3 };

Union initialization

union {
      char birthday[9];
      int age;
      float weight;
} people = { .age = 14 };

printf format

%[flags][min field width][precision][length]conversion specifier


   #	Alternate
   0	zero pad
   -	left align
   +	explicit + - sign
     	space for + sign
   '	locale thousands grouping
   I	Use locale's alt digits  

min field width: #,*

precision: .#, .*

   hh	char
   h	short
   l	long
   ll	long long
   j	[u]intmax_t
   z	size_t
   t	ptrdiff_t
   L	long double

conversion specifier:
   c	unsigned char
   d	signed int
   u	unsigned int
   x	unsigned hex int
   X	unsigned HEX int
   e	[-]d.ddde±dd double,
   E	[-]d.dddE±dd double


printf("%08X", var);		00001234
printf("%20s","string");	string (right aligned)
printf("%*s", 20, "string");	string (right aligned, the alignment is specified as an argument)
printf("%-20s", "string");	string (left aligned)
printf("%-20.20s", "string");	string (the string is truncated if it is too long)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s