How to use the type cast operator in C Programming

/*
* Program to use the type cast operator
* From the book: Visual Quickstart Guide C Programming
*/

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

/* 
* Begin main function
*/

int main(void) {

/*
* Define and initialize a void pointer
* variable. It's good practice to
* initialize pointer variables with 
* the NULL pointer value since it makes
* it clear that x points to nothing.
*/

void *x = NULL;

/*
* Call the malloc() function and ask for
* a block of memory big enough to hold 
* an integer. Store the address of the 
* block returned by malloc() in the void
 * pointer variable. Since the amount of
 * memory required to store an integer is
 * machine-dependant, you have to use the
 * sizeof() operator to find how many 
 * bytes will be required.
 */
 
 x = malloc(sizeof(int));
 
 /*
 * Print the address of the block.
 */
 
 printf("Starting address: %p.\n", x);
 
 /*
 * Store an integer value into the memory
 * block using the type cast and 
 * dereferencing operators. The x refers 
 * to the address of the dynamically
 * reserved memory block. The (int *) 
 * before the x type-casts that as an
 * integer. Finally, the dereferencing 
 * operator (the initial *) allows you to
 * read from or write to the memory block.
 */
 
 *(int *)x = 1234;
 
 /* 
 * Print the value stored in the memory
 * block. Just as you can use a combination
 * of the type cast and dereferencing operators
 * to assign a variable a memory block, the
 * combination of the two can be used to read
 * in a value stored in a memory block. The %d
 * signifier is used since the value stored is
 * an integer.
  */
 
 printf("Value stored in the memory block: %d. \n" , *(int *)x);
 
 /*
 * Return the block to the pool using the
 * free() function.
 */
 
 free(x);
 x = NULL;
 
 /*
 * Complete the main function
 */
 
 getchar();
 return 0;
 }
 
 

How pickling works in Python 3

# Original source code found at:
# http://pythonelcric.blogspot.ca/2012/12/python-pickle.html

import pickle

def main():

    # Creating objects we want to pickle, write, to a file.
    pickleObjects = ["home", "library", "garage", "garden", "pool", "car"]
    print (pickleObjects)

    # Pickling, writing, to a file.
    outFile = open('pickleExample.txt', 'wb')
    pickle.dump(pickleObjects, outFile)
    outFile.close()

    # Un-pickling, reading, from a file.
    inFile = open('pickleExample.txt', 'rb')
    unPickledObjects = pickle.load(inFile)
    print (unPickledObjects)
    inFile.close()

if __name__ == '__main__':
    main()

How to request and return dynamic memory in C Programming

/*
* Program to request and return dynamic memory
* From the book: Visual Quickstart Guide C Programming
*/

#include <stdio.h>
/*
* The inclusion of the stdlib.h header file
* provides the declarations for the malloc()
* and free() functions.
*/
#include <stdlib.h>

/*
* Begin main function
*/
int main(void) {

/* 
* Define a void pointer variable
*/

void *x;

/*
* Call the malloc() function to request a block
* of memory 1000 bytes long. The address
* returned by the malloc() function, which
* indicates the starting address of the
* requested block of memory will be assiged to
* the void pointer x.
*/

x = malloc(1000);

/*
* Print the address. To allow you to confirm 
* that the process worked and view the minimal
* results, the address stored in the void pointer
* will be printed. The %p signifier is used, since
* x is a pointer.
*/

printf("Starting block address: %p. \n", x);

/*
* Return the block to the pool using the free() 
* function. The free() function takes one 
* argument: the address ofthe block to be 
* returned to the pool. After this call to free(),
* the specific block of memory pointed to by the
* address may no longer be used by the program.
* In other words, referring to x may cause
* problems since it no longer points to a reserved
* block of memory. For this reason, the second
*line sets teh value of x to NULL.
*/

free(x);
x = NULL;

/*
* Complete the main function
*/

getchar();
return 0;
}

How to use program arguments in C Programming

/* 
* A program that prints the arguments given
* to the program and displays the memory
* locations. C programs can acess their 
* command-line arguements through an array
* of pointers to strings.
*
From the book: Visual Quickstart Guide C Programming
*/

#include <stdio.h>

/*
* Begin the main function which takes two arguements.
* char *argv[] is the equivalent of saying "argv is an
* array (of unknown size) of pointers to character
* variables.
*/

int main(int argc, char *argv[]) {

/*
* Define and initalize an integer i to be used as
* loop index variable
*/

int i;

/* 
* Print the argument count. When the program runs, the
* argc variable will be assigned to the number of arguments 
* the application received. This value is first printed.
*/

printf("Number of arguments received: %d\n", argc);

/*
* The array's base address (the location where the array's
* first element is stored) is printed.
*/

printf("argv base address: %p\n\n", argv);

/*
* Add a loop that prints out the addresses and values of each
* recieved argument. The loops goes from 0 (the first item 
* in the argv array) to one less than the number of arguments 
* recieved (argc). For every element in the argv pointer 
* array, this loop will first print the actual address
* stored in that element using the %p sequence. Then the
* characters string that starts at that address will be
* printed as a string. The last value corresponds to
* the actual command-line argument.
*/

printf("Address --> Value\n");

for (i = 0; i < argc; i++) {
printf("%p --> %s\n", argv[i], argv[i]);
}

/*
* Complete the main function
*/

getchar();
return 0;
}

Understanding command-line arguments in C Programming

Adapted from the book: Visual Quickstart Guide C Programming

When you run a complied C program, you can use the command-line to optionally add a variable number of arguments that are then passed to that program. The arguments are separated by one or more blank spaces and come after the application name.

So how can your C program access these arguments when it may not now how many there are? C always passes two parameters to your main function: the first one is an integer with the number of arguments the application received, and the second one is an array of pointers to where those arguments have been stored in memory.

By convention, the first parameter is named argc (for argument count) and the second one argv (for argument vector, where vector means array). Each string (which is to say each argument) is a character array, terminated with a null byte. There is always at least one argument because C inserts the program name in front of the list of arguments.

Understanding encapsulation in Python Programming

Adapted from the book: Python Programming for the Absolute Beginner

No variables that you create in a function, including its parameters can be directly accessed outside of its function. Encapsulation helps keep independent code truly separate by hiding or encapsulating the details. You use parameters and return values to communicate just the information that needs to be exchanged. You don’t have to keep track of variables you create think a function in the rest of your program. This may not seem like a benefit when you are making small programs but as your programs get large it will become one.

Encapsulation is a principle of abstraction so therefore they are closely related. Abstraction saves you from worrying about the details. Encapsulation hides details from you.

Through the magic of encapsulation,  functions can be totally sealed off and independent from each other and the main part of  your program so that the only way you can get information into them is through their parameters and the only way to get information out of them is from their return values. Well, that isn’t completely true. There is another way you can share the information among parts of your program: through global variables but that is a story for another time.

Reading from text files in Python Programming

Adapted from the book: Python Programming for the Absolute Beginner

With Python, its easy to read strings from plain text files, files that are made up of only ASCII characters. There are many different types of text files, plain text files are a good choice for permanently storing simple information, for a number of reasons. First, plain text files are cross-platform. A plain text file on a Windows machine is the same plain text file on a Mac and is the same plain text file under UNIX. Second, plain text files are easy to use. Most operating systems come with basic tools to view and edit them.

How to Store Complex Data in Files in Python Programming

From the book: Python Programming for the Absolute Beginner

Text files are convenient because you can read and manipulate them with any text editor, but they are limited to storing a series of characters. Sometimes you may want to store more complex information, such as a list or a dictionary for example. You could try to convert the contents of these data structures into chrcters and save them to a file, but Python offers a much better way. You can store more complex data in a file with a single line of code. You can even store a simple database of values in a single file that acts like a dictionary.

Pickling means to preserve and that’s just what it means in Python. You can pickle a complex piece of data, such as a list or dictionary, and save it in its entirety to a file.

Other languages can covert complex data for store in files too, but may not call the process pickling. Instead, these languages may call the process serialization or marshaling.

How to write a list of strings to a text file in Python Programming

# Writing a List of Strings to a Text File
# From the book: Python Programming for the Absolute Beginner
#
# Like its counterpart, readlines()
# writelines() works with a list of strings
# But instead of reading a text file into a list
# the method writes a list of strings to a file

# Open the file for writing which means that you will wipe out
# any existing file and start with a new, empty one. 

print("\nCreating a text file with the writelines() method.")
text_file = open("write_it.txt", "w")

# Create a list of strings to be written, in order, to the file inserting
# newline characters where you want them in the text file.

lines =["Line 1\n",
        "This is line 2\n",
        "That makes this line 3\n"]

# Write the entire list of strings to the file with the
# writelines() method

text_file.writelines(lines)

# Close the file

text_file.close()

# Print out the contents of the file to show that the new file

print("\nReading the newly created file.")
text_file = open("write_it.txt", "r")

print(text_file.read())
text_file.close()

input("\n\nPress the enter key to exit.")

How to use pointer arithmetic to access arrays in C Programming

/*
* Program to use pointer arithmetic to access array
* From the book: Visual Quickstart Guide C Programming
*/

#include <stdio.h>

/*
* Define a C preprocessor constant called COUNT
* with the value 5. This value will be used to
* control the loop for acessing every array element
*/

#define COUNT 5

/*
* Begin Main Function
*/

int main (void) {

/*
* Define and initialize an array of chars a with
* five elements. Then define a char pointer variable b
* and an integer variable i as a loop control variable
*/

char a[] = {3, 23, 14, 7, 12};
char *b;
int i;

/*
* Assign a's base address to the b pointer varaible
* a[0] and *b are now eqivalent and refer to the first
* elements value
*/

b = a;

/* 
* Use a for loop to print the values of all elements of
* the a array. This first loop uses the array subscript 
* operator and the index of the elements to access every
* array value. a[i] is type casted to an integer value to 
* avoid problems on some systems
*/

printf("Using subscript\n");
for (i = 0; i < COUNT; i++) 
{
printf("%d\n", (int) a[i]);
}

/*
* Add a second for loop to print all the elemets again using
* pointer arthemetic. In this loop, instead of using the
* subscription operator (the square brackets), pointers will 
* access each element. Using the dereferencing operator(*), the
* value *b points to the value stored in a particular memory block
* The first tine the loop runs, *b points to a[0].  This value is
* printed and then b is incremented, so that it points to the next
* array element (a[1]). The process continues through the entire loop.
* Again, the deference value (*b) is type casted to avoid problems.
*/

printf("Using pointer\n");

for(i =0; i < COUNT; i++)
{
printf("%d\n", (int) *b);
b++;
}

/*
* End of Main function
*/

getchar();
return 0;
}