Monthly Archive: January 2011

The C NULL Pointer

NULL is a #define statement that is used by functions in the standard C library (stdlib.h) such as malloc and fopen. It’s used to define an invalid pointer or an error condition.

Here is NULL definition statement inside stdlib.h:

#define NULL ((void *)0)

The above code means that NULL is the zero memory address.

Note that unlike PHP, the following is bad practice in C language:

if (!malloc(10))

You need to write the above statement as follows:

if (malloc(10) == NULL)

Below is the sample code for the NULL pointer:

/*
 *
 * null.c
 *
 * Program to demonstrate the use of a NULL pointer
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

static void goodbye() {
	while (getchar() != 'n') {}
	printf("nPress ENTER to exit: ");
	fflush(stdin);
	getchar();
}

/*
 *
 * memdup()
 *
 * A function that takes a pointer to any type of memory,
 * then creates a duplicate amount of memory (using malloc)
 * and copies the original memory into the new memory
 *
 */

void *memdup(void *mem, int size) {
	void *newptr;

	newptr = malloc(size);
	if (newptr == NULL) {
		return NULL;
	}
	memcpy(newptr, mem, size);
	return newptr;
}

main() {
	float float_array1[] = {1.2, 2.3, 3.4};
	int int_array1[] = {1,2,3,4,5,6};
	char char_array1[] = "Hello Worldn";
	float *float_array2;
	int *int_array2;
	char *char_array2;

	atexit(goodbye);

	float_array2 = memdup(float_array1, sizeof float_array1);
	int_array2 = memdup(int_array1, sizeof int_array1);
	char_array2 = memdup(char_array1, sizeof char_array1);

	if (float_array2 == NULL) {
		printf("The float failedn");
	}
	else {
		free(float_array2);
	}

	int_array2 == NULL ? printf("The int failedn") : free(int_array2);

	char_array2 == NULL && printf("The char failedn");

	return 0;
}

C void Pointers

A void pointer is a generic pointer which has no variable type. It’s primary used for declaring an “universal” pointer (“pointer to anything”).

For example in the following code, free_it function is not defined:

int *int_ptr = malloc(10 * sizeof(int));
float *float_ptr = malloc(10 * sizeof(float));
free_it(int_ptr);    // int_ptr is an integer
free_it(float_ptr);    // float_ptr is a float

Notice in the above code, although the free_it function is not defined, it can take different variable types as its parameter. It is able to define a parameter that can accept all kinds of variable types by declaring the parameter as void:

void *ptr;

Void pointers can be used by these functions: malloc, free, memcpy, and memset, etc.

The void variable type does not have size. Therefore, the following statements are undefined:

// void *ptr;
sizeof *ptr;    // undefined
ptr[0];    // undefined

To use a void pointer, assign its address to another non-void pointer before using it, for instance:

emp *el = ptr;    // or
int *el = ptr;

Below is the sample code for the void pointers:

/*
 *
 * void.c
 *
 * Program to demonstrate the use of a void pointer
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdlib.h>
#include <memory.h>

/*
 *
 * memdup()
 *
 * A function that takes a pointer to any type of memory,
 * then creates a duplicate amount of memory (using malloc)
 * and copies the original memory into the new memory
 *
 */

void *memdup (void *mem, int size) {
	void *newptr;

	newptr = malloc(size);
	memcpy(newptr, mem, size);
	return newptr;

	// could be written: return memcpy(malloc(size), mem, size);
}

main() {
	float float_array1[] = {1.2, 2.3, 3.4};
	int int_array1[] = {1, 2, 3, 4, 5, 6};
	char char_array1[] = "Hello Worldn";
	float *float_array2;
	int *int_array2;
	char *char_array2;

	float_array2 = memdup(float_array1, sizeof float_array1);
	int_array2 = memdup(int_array1, sizeof int_array1);
	char_array2 = memdup(char_array1, sizeof char_array1);

	free(float_array2);
	free(int_array2);
	free(char_array2);
}

The above code does not print out anything, just to show you how to use the void pointers.

If you have any questions about the above code, leave a comment below and I will respond as quickly as possible.

The C Bit-Sized Structure Fields

Fields of structures can be sized in multiples of 1 bit. For instance,

struct employee {
 char name[31];
 int married :1;
};

Note that in the above structure, :1 represents the single bit for married integer variable.

These type of fields are called small integer types.

It’s a good practice to place these bit-sized fields continuously in a structure definition for the minimal waste of space.

Here is the sample code for bit-sized structure fields rewrote from the last post:

/*
 *
 * bitfield.c
 *
 * Program to demonstrate the use of bit-sized structure fields
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct employee {
 char name[31];
 char address[101];
 int age;
 float salary;
 int married :1;
 int manager :1;
 int male :1;
 int num_kids :4; // limit of 15 kids
};

typedef struct employee emp;

static read_emp(emp *e) {
 char answer;

 printf("Please enter the age: ");
 scanf("%d", &e->age);

 while (getchar() != 'n') {}

 printf("Married (Y/N)? ");
 fflush(stdin);
 answer = getchar();
 e->married = toupper(answer) == 'Y';
}

static void print_emp(emp *e) {
 printf("Age is %dn", e->age);
 puts(e->married ? "Married" : "Not married");
}

static void goodbye() {
 while (getchar() != 'n') {}
 printf("nPress ENTER to exit: ");
 fflush(stdin);
 getchar();
}

main() {
 emp e;

 read_emp(&e);
 print_emp(&e);

 fflush(stdin);
}

The C & and | Operators

These operators are bitwise operators, different from the logical operators (&& and ||).

The & (Bitwise and) operator can produce the following results:

  • If a bit is on in both operands, it’s on in the result
  • If a bit is off in either operand, it’s off in the result

Notice the difference between single (&, |) operator and double (&&, ||) operator. The double operator works on the entire number, whereas single operator works on each bit in the number.

The | (Bitwise or) operator is almost the same as & operator:

  • If a bit is on in either operand, it’s on in the result
  • If a bit is off in both operands, it’s off in the result

Here are some examples:

104 & 3 = 8
104 (01101000)
 13 (00001101)
  8 (00001000)
  // There is only one bit that is on on both operands, therefore the result is only on for this particular bit.

52 | 12 = 60
52 (00110100)
12 (00001100)
60 (00111100)
  // There needs to be at least one bit on on either operand in order for the result to be on, therefore the result is on for the bits which are on for either operands.

The usage of these two operator is just turning a bit on or off.

Below is the code for turning a bit on:

#define MARRIED (1 << 3)
status |= MARRIED;    // is the same as status = status | MARRIED

And turning a bit off:

status &= ~MARRIED;

For testing whether a bit is on or off:

if (status & MARRIED)
if (!(status & MARRIED))

It will return a zero (off/false) or a non-zero (on/true).

Note that these two operators have lower precedence than –, !-, etc. and the follwing wil not work:

if (status & MARRIED == 0)    // Its first step will be to process MARRIED == 0 which will always produce the unexpected answer.

Here is the sample code for the two operators:

/*
 *
 * and_or.c
 *
 * Program to demonstrate the use of bit-sized & and | operators
 *
 * by Mark Virtue, 2001.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MARRIED (1 << 0)
#define MANAGER (1 << 1)
#define MALE (1 << 2)

struct employee {
	char name[31];
	char address[101];
	int age;
	float salary;
	int flags;
};

typedef struct employee emp;

static read_emp(emp *e) {
	char answer;

	e->flags = 0;

	printf("Please enter the age: ");
	scanf("%d", &e->age);

	while (getchar() != 'n') {}

	printf("Married (Y/N)? ");
	fflush(stdin);
	answer = getchar();
	if (toupper(answer) == 'Y') {
		e->flags |= MARRIED;
	}
	else {
		e->flags &= ~MARRIED;
	}
}

static void print_emp(emp *e) {
	printf("Age is %dn", e->age);
	puts((e->flags & MARRIED) ? "Married" : "Not married");
}

static void goodbye() {
	while (getchar() != 'n') {}
	printf("nPress ENTER to exit: ");
	fflush(stdin);
	getchar();
}

main() {
	emp e;

	read_emp(&e);
	print_emp(&e);

	fflush(stdin);
}

The C ~ Operator

The ~ operator is an unary operator, means that it only works with one number. I don’t know what is the ~ called. It’s kinda like – (negative) operator.

It’s used to reverse each bit in the bit pattern of the number. This means that it turns 0 to 1 and vise versa.

The following example uses 8-bit numbers:

~211 = 44
211 (11010011)
 44 (00101100)

The sum of the numbers in the above example is the largest 8-bit number (255).

211 + 44 = 255

Here is the example code for the ~ operator:

/*
 *
 * complement.c
 *
 * Program to demonstrate the ones complement (~) operator
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>
#include <stdlib.h>

static void goodbye() {
	while (getchar() != 'n') {}
	printf("nPress ENTER to exit: ");
	fflush(stdin);
	getchar();
}

main() {
	unsigned int number;
	unsigned char result;	// We shall use 8-bit demonstrations

	atexit(goodbye);

	printf("Please enter a number: ");
	scanf("%d", &number);

	result = ~number;

	printf("The ones complement of %u (hex %X) is %u (hex %X)n", number, number, result, result);

	return 0;
}

If you have any issue compiling the above code or question about this post, leave a comment below and I will be happy to help you.

The C Shift-left and Shift-right Bitwise Operators

This is the continuation of the C programming tutorial series from the last post which I wrote Dec 7 of last year.

The shift-left operator (<<, or double left) is used to shift the bit pattern of a number by a certain number of bits to the left.

The shift-right operator (>>, or double right) is used to shift this bit pattern to the opposite direction (right).

For example, the bit pattern of five (5) is 101. The result bit pattern of shifting it 4 bits to the left is 1010000.

If shifting left are too far such as 50, it will produce undefined results, while right shifting too far will simply be truncated.

Here is an example of shift-left operator:

13<<3=104
 13 (00001101)
104 (01101000)

The bit pattern between 13 and 104 is exactly shifted left 3 places.

Notice the division of 104 and 13 is exactly 8, which is 2 to the power of 3, which means

13*2^3=104

which is almost the same as the above statement with shift-left operator.

Here is another example for the shift-right operator:

52>>4=3
52 (00110100)
 3 (00000011)

The bit pattern between 52 and 3 is shifted right 4 spaces, which removed the last 4 digit (0100) which is the reminder of 3.

This is exactly the same as the last example except this one is divide by 2 to the power of 4:

52 / 2^4 = 3

Note that this is integer division, therefore there is no remainder or decimal.

Based on the above examples, you can see that shifting left is multiply by 2 and sifting right is divide by 2.

Below is the example code for the shift operators:

/*
 * shift.c
 *
 * Program to demonstrate the shift left and right operators
 *
 * by Mark Virtue, 2001.
 *
 */

 #include <stdio.h>
 #include <stdlib.h>

 static void goodbye() {
 	while (getchar() != 'n') {};
 	printf("nPress ENTER to exit: ");
 	fflush(stdin);
 	getchar();
 }

 main() {
 	unsigned int number;
 	int shift;
 	unsigned int result;

 	atexit(goodbye);

 	printf("Please enter a number: ");
 	scanf("%d", &number);
 	printf("How many bits would you like to shift (negative to shift right)? ");
 	scanf("%d", &shift);

 	if (shift >= 0) {
 		result = number << shift;
 	}
 	else {
 		result = number >> -shift;
 	}

 	printf("%u (hex %X) shifted %s %d is %u (hex %X)n",
 		number, number,
 		shift >= 0 ? "left" : "right",
 		shift >= 0 ? shift : -shift,
 		result, result);

 	return 0;
 }

If you have any issue compiling the above code or any question regarding this post, leave a comment below and I will help you ASAP.

Creating an even Simpler Framework than MVC – Part 2

I discussed a little bit about this mini-framework in part 1. Today I rewrote the whole code for the index.php to be more configurable, and I added another folder for storing PHP pages. And yes, it includes the automatic page title generation.

It’s up to you to create other folders for the includes, images, and other files, but the PHP pages folder is a must have. Without this folder, the framework will grab the original page without process through the framework.

Let’s begin.

I need to first introduce the basic folder structure for the framework:

Note that I’ve included lessPHP inside the css folder to make writing styles easier.

The .htaccess file in the root folder is exactly the same as part 1‘s:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>

However, the one in the pages folder is different:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteRule ^(.*)$ ../$1 [L]
</IfModule>

As those of you who understands the Apache better knows, the above code acts like access rejection. It means that whenever someone tries to access the pages folder or one of the files within it, this code will automatically rewrite the URL to the root folder. Note the difference between rewrite and redirect.

The pages folder is kinda like public or webroot folder, except it’s only used for PHP pages, not for images, stylesheets, Javascripts, or any other files.

Now the most important file, index.php. This file is placed in the root folder, and contains the most important code in the whole framework. I also added page title generation in this file as stated before.

[php]
<?php
	// Variables configuration
$rootDir = dirname(__FILE__) . "/";
$mainDir = "pages/";
$appDir = $rootDir . $mainDir;
if (isset($_GET['url'])):
	$url = $_GET['url'];
	$path = $appDir . $url . ".php";
else:
	$path = $appDir . "index.php";
endif;
if (!file_exists($path)):
	$path = $appDir . 'notfound.php';
	$title = "Page not found";
endif;

	// Set page title
	// First set the page title from the the title variable from the individual page if presented
foreach (file($path) as $content):
	if (strstr($content, "title")):
		if (strstr($content, """)):
			$quote = """;
		else:
			$quote = "'";
		endif;
		$titleVar = explode($quote, $content);
		$title = $titleVar[1];
	endif;
endforeach;
	// Process the URL as the page title if title variable is not set
if (empty($title)):
	$urlPath = explode("/", $_SERVER['REQUEST_URI']);
	$titleVar = (string)$urlPath[sizeof($urlPath)-1];
	$title = "";
	for ($i=0; $i < strlen($titleVar); ++$i):
		if ($titleVar{$i} == strtoupper($titleVar{$i})):
			$title .= " ";
		endif;
	$title .= $titleVar{$i};
	endfor;
	$title = ucfirst($title);
endif;

	// Include the neccesary pages
include_once $rootDir . 'includes/header.php';
include_once $path;
include_once $rootDir . 'includes/footer.php';
?>
[/php]

As you have noticed, I’m using URL to auto-generate the page title. You can also set the page title for each page using the $title variable.

The $mainDir variable is configurable, so you can rename the pages folder to whatever you want.

That’s it. If you don’t count the img, css, and js folder and files inside them, the files for the framework would be total of 7 files.

Here is the completed files.

If you have any issues working with this mini-framework, leave a comment below and I will happy to help you.

Creating an even Simpler Framework than MVC Framework – Part 1 (Updated)

Update: I rewrote the code for the framework and added page title generation as well, take a look at part 2.

After building and digging through the source of the simple MVC framework provided by Anant Garg, I was able to discover the true nature of the MVC framework. Actually, I’m able to modify his framework to an even simpler framework which just use View and a little Controller in the MVC (Model-View-Controller) with no database connectivity.

The primary use for the MVC pattern is to work with the database. However, sometimes we don’t need to use database to creating a web site. According to my own knowledge, the Model is used to interact with the database and the Controller uses logical to process the database.

I stated that I need to use “a little” Controller because it also controls which page to display and sends it to the View.

In this simple framework (and perhaps all of the MVC frameworks), the most important file is .htaccess which controls the URL. Here is the content of the file copied directly from Anant’s post:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

</IfModule>

Note that this .htaccess file needs to place in th root directory of your web site instead of public folder because we will be creating a framework that has no directory. You can create public folder or webroot folder if you want, but make sure to change the following code accordingly.

The above code converts the URL path to the url query. For example, the URL http://localhost/mvc/test would be converted to http://localhost/index.php?url=mvc/test.

Next step is to create the index.php file which used to process the url query:

<?php
	if (isset($_GET['url'])):
		$url = $_GET['url'];
		$path = "{$url}.php";
	else:
		$path = "home.php";
	endif;

	include_once 'includes/header.php';
	if (file_exists($path)):
		include_once $path;
	else:
		include_once 'notfound.php';
	endif;
	include_once 'includes/footer.php';
?>

This is what I called “reverse include”, because I had always been include header and footer manually on every page until I found CakePHP MVC framework.

I also stated that this framework will not have any folder. Well, to include header and footer, you need to create an includes folder to place all the repeatable scripts, unless you really want to be disorganized :) .

Congratulation, you just created a mini framework. Note that this framework is used for small websites or personal sites where the database is not used at all. This means that it doesn’t have a back-end to edit the page directly on the server.

However, there is also an advantage to it. You don’t need to include the header and footer manually when creating a new page. It will include them automatically. It also can direct to the custom page if the specified page is not found.

About the title issue: I haven’t found a solution to set the title on individual page yet. Right now the title in the header is static. I will update this post once I find a solution to this issue.

Feel free to discuss this framework with me in the comment below.

Write CSS3 with Understandable Variables with LessPHP – Part 3

LessPHP allows you to use variables in your CSS stylesheet for the repeatable blocks of code.

In part 2, I provided you with the content of var.less. This part I will give you an example on how to use this .less file to write your own stylesheet. The provided example is based on the final project of this post on the Nettuts+.

First off, here is the folder structure for this example:

Example folder structure

Folder structure for the example

From top to bottom, they are:

css - folder

less - folder

lessc.inc.php in less folder - LessPHP compiler

main.less in less folder - source file to compile to CSS stylesheet

@import 'var';

body, html {
	@dimension(100%;100%);
}

body {
	@center;
}

#box {
  @bg-color(#e3e3e3);
  @dimension(400px;200px);
  @transition(all;1s);
  border: 1px dashed #666;
  margin: auto;
  cursor: pointer;
  position: relative;
 	:after {
 		@dimension(70%;10px);
 		@box-shadow(0;9px;20px;rgba(0,0,0,.4));
	  content: '';
	  position: absolute;
	  bottom: 0;
	  left: 15%;
	  z-index: -1;
	}
	> div {
  	@bg-color(#e3e3e3);
    @dimension(100%;100%);
    @transition(all;1s;ease-in-out);
    position: absolute;
    top: 0;
    left: 0;
    font: 45px/200px bold helvetica, arial, sans-serif;
    text-align: center;
  	:first-child {
	    position: relative;
  	  z-index: 2;
    }
 }
 :hover {
 	@rotate(;rotateY(180deg));
 	> div:first-child {
  	opacity: 0;
 	}
	div:last-child {
  	@rotate(rotateY(180deg));
 	}
 }
}



var.less in less folder - contains the LessPHP variables which I already provided it to you in part 2

index.php in css folder – contains the compile script which provided in part 1

main.css in css folder – contains the compiled CSS styles

index.php in root folder – contains the inclusion of main.css in css folder

Note that some of the code are directly copied from the above source. Also, in order to completely experience this example, you need to use Chrome or webkit compatible browsers.

Feel free to ask any question you have regarding the above code in the comment below.