egsoftweb@gmail.com
 facebook.com/egsoftweb

Welcome to EGSoftWeb

Programming
Blogs and Tutorials

Blogs on programming, technology and programming tutorials.

Desktop
Application

Antivirus, encryption/decryption, folder locking tools and miscellaneous desktop applications.

Programming Library

C++ drawing library for plotting shape in 2D, 3D, animation and many other functions.

Android
Application

Just gambling around the android programming and need to make a few useful android applications and tricky android puzzle games.

Dynamic memory allocation

 c tutorials |  Admin

If size of array we declared is not fix, then we can allocate memory manually during run-time using inbuilt function like malloc, alloc etc.

This is known as dynamic memory allocation.

There are 4 library functions defined in <stdlib.h> makes dynamic memory allocation in C programming. These are malloc(), calloc(), realloc() and free().


1) malloc() - The name "malloc" stands for memory allocation.

The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form.

Syntax of malloc():

ptr = (cast_type*) malloc(byte_size)

 

Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

However, if the space is insufficient, allocation fails then returns a NULL pointer.

 

2) calloc() - The name "calloc" stands for contiguous allocation.

The malloc() function allocates a single block of memory. Whereas, calloc() allocates multiple blocks of memory and initializes them to zero.

Syntax of calloc()-

ptr = (cast_type*)calloc(n, element_size);

 

This statement allocates contiguous space in memory for n elements each with the size of element_size.

 

3) free() - Dynamically allocated memory created with either calloc() or malloc() doesn`t get freed on their own. We must use free() to release the space.

Syntax of free()-

free(ptr);

 

This statement frees the space allocated in the memory pointed by ptr.

 

4) realloc() - If the dynamically allocated memory is insufficient or more than required, we can change the size of previously allocated memory using realloc() function.

Syntax of realloc()-

ptr = realloc(ptr, x);

Here, ptr is reallocated with new size x.

Examples:

Pointers

 c tutorials |  Admin

What Are Pointers?

A pointer is a variable that holds a memory address. This address is the location of another object (typically another variable) in memory.

For example, if one variable contains the address of another variable, the first variable is said to “pointer to the second”.

Suppose second variable is an int type then the first variable`s type is called “pointer to integer” (int*)

 

Why pointers are used:

1) Pointers can be used in functions so that their calling arguments could be modified

2) Pointers support dynamic memory allocation.

3) Pointers can improve the efficiency of certain routines().

4) Pointers provide support for dynamic data structures, such as binary trees and linked lists.

 

Use pointers carefully:

Pointers are one of the strongest but also one of the most dangerous features in C/C++.

For example, a pointer containing an invalid value can cause a program to crash.

Using pointers incorrectly, causing bugs that are very difficult to find.

 

Pointer Variables:

A pointer must be declared before we use it. A pointer declaration consists of a base type, an *, and the variable name. The general form for declaring a pointer variable is

            type *name;

 

where type is the base type of the pointer and may be any valid type. The name of the pointer variable is specified by name.

 

1) The base type of the pointer defines the type of object to which the pointer will point.

2) any type of pointer can point anywhere in memory.

3) all pointer operations are done relative to the pointer`s base type.

(an int * pointer always "thinks" that it points to an int object, no matter what that piece of memory actually contains.)

 

The Pointer Operators:

There are two pointer operators: * and &.

The & is a unary operator that returns the memory address of its operand & called as reference operator. (Or we speak it ampersand

m = &count;

places into m the memory address of the variable count.

 

This address is the computer`s internal location of the variable. It has nothing to do with the value of count. We can think of & as "the address of." Therefore,  m=&count means "m receives the address of count".

for example: if the variable count uses memory location 2000 to store its value, Also suppose that count has a value of 100. Then, m=&count means, m will have the value 2000.

 

pointer operator, *, is the complement of &.

It is a unary operator that returns the value located at the address that follows. For example, if m contains the memory address of the variable count,

q = *m;

 assigns the value of count into q. Thus, q will have the value 100 because 100 is stored at location 2000, which is the memory address that was stored in m. we can think of * as "at address." In this case, the preceding statement can be said as "q receives the value at address m".

 

Pointer Expressions:

i)                 Pointer Assignments:

We can use a pointer on the right-hand side of an assignment statement to assign its value to another pointer, when both pointers are the same type.

Example:

Strings

 c tutorials |  Admin

String is a simply an array of characters terminated by a null (or null character).

Or

A string is a null-terminated character array. (A null is zero.)

Or

A string contains the characters that make up the string followed by a null.

 

When declaring a character array that will hold a string, you need to declare it to be one character longer than the largest string that it will hold. For example, to declare an array str that can hold a 10-character string, we would write

char str[11];

Specifying 11 for the size makes room for the null at the end of the string.

 

When we use a quoted string constant in our program, we are also creating a null-terminated string. A string constant is a list of characters enclosed in double quotes.

Example: "hello there, this is a string"

 

Character arrays that hold strings allow a shorthand initialization that takes the form:

char  str[size] = "this is string";

This is the same as writing

char  str[size] = { `t`, `h`, `i`, `s`, ` `, `i`, `s`, ` `, `s`, `t`, `r`, `i`, `n`, `g`, `\0` };

Because strings end with a null. We can also put 0 in place of `\0`.

This is why str is 15 characters long even though "this is string" is only 14.

When we use the string constant, the compiler automatically supplies the null terminator.

We do not need to add the null to the end of string constants manually— the compiler does this automatically.

 

[Note: C++ also defines a string class, called string, which provides an object-oriented approach to string handling, but it is not supported by C.]

 

C supports a wide range of functions in <string.h> header that manipulate strings.

The most common are listed here:

 

Name Function

strcpy(s1, s2)              Copies s2 into s1

strcat(s1, s2)               Concatenates s2 onto the end of s1

strlen(s1)                    Returns the length of s1

strcmp(s1, s2)             Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2

strchr(s1, ch)               Returns a pointer to the first occurrence of ch in s1

strstr(s1, s2)                Returns a pointer to the first occurrence of s2 in s1

 

Arrays of Strings:

To create an array of strings, we use a two-dimensional character array. The size of the left dimension determines the number of strings, and the size of the right dimension specifies the maximum length of each string. The following declares an array of 30 strings, each with a maximum length of 79 characters:

char str_array[30][80];

 

It is easy to access an individual string: we simply specify only the left index. For example, the following statement calls gets( ) with the third string in str_array.

gets(str_array[2]);

The preceding statement is functionally equivalent to

gets(&str_array[2][0]);

 

Examples:

Two and Multi Dimensional Array

 c tutorials |  Admin

Two Dimensional Array:

A two-dimensional array is, essentially, an array of one-dimensional arrays. To declare a two-dimensional integer array d of size 10, 20 (10x20), we would write

int d[10][20];

to access point 1,2 of array d, we would use d[1][2].

Example:

The following example loads a two-dimensional array with the numbers 1 through 12 and prints them row by row.

#include <stdio.h>

int main(void)

{

     int i, j, t, num[3][4];

     for (i = 0; i<3; ++i)

     {

           for (j = 0; j<4; ++j)

           {

                num[i][j] = (i * 4) + j + 1;

           }

     }

     /* now print them out */

     for (t = 0; t<3; ++t)

     {

           for (i = 0; i<4; ++i)

           {

                printf(" % 3d ", num[t] [i]);

           }

           printf("\n");

     }

     getchar();

     return 0;

}

 

In this example, num[0][0] has the value 1, num[0][1] the value 2, num[0][2] the value 3, and so on. The value of num[2][3] will be 12.

Two-dimensional arrays are stored in a row-column matrix, where the left index indicates the row and the right indicates the column. This means that the rightmost index changes faster than the leftmost when accessing the elements in the array in the order in which they are actually stored in memory.

 

In the case of a two-dimensional array, the following formula yields the number of bytes of memory needed to hold it:

bytes = size of 1st index × size of 2nd index × sizeof(base type)

 

or we can define

#define ARRAYSIZE(A) = sizeof(A)/sizeof(A[0][0])

 

Example: