Algorithm & Programming Session #05

Back again to another session of algorithm. In this post I’ll be talking(mostly typing) about Pointers and Arrays.

The sub topics are:

1. Pointer Definition

2. Pointer Concept

3. Pointer to Pointer

4. Array

&String

What is pointer?  Pointer is a variable used to keep an address of another variable.

Syntax :
*ptr_name;
Two operators mostly used in pointer : * (content of) and & (address of)

Example :

Initialize an integer pointer into a data variable:
int i, *ptr;
ptr = &i;
To assign a new value to the variable pointed by the pointer:
*ptr = 5; /* means i=5 */

 

Pointer to Pointer is basically the same like what a pointer does but instead you do it to another pointer. So it’s like pointerception or something like that.

Syntax:
**ptr_ptr ;

Example:

int i, *ptr, **ptr_ptr;
ptr = &i;
ptr_ptr = &ptr;
To assign new value to i:
*ptr = 5; // means i=5 ;
**ptr_ptr = 9; // means i=9; or *ptr=9;

Next is array. Array is data that is kept into a certain variable so we could access them for future usage. Usually array is used to make things tidier since it makes a variable with a lot of data instead of a lot variables.

Array has characteristics and those are:

Homogenous: All elements have similar data type
Random Access: Each element can be reached individually, does not have to be sequential

Arrays usually consist of these set components:
Identifier (name of array)
Dimensional value inside operator [ ]; Example : int x[50];

Arrays can be initialized with no dimensions example: int x[ ] = {1, 2, -4, 8};

The number 1 2 -4 8 means that the array has 4 elements.

Examples with dimension:

x[8]={1, 2, -4, 8};

That means the array has 8 elements but visualized like so:

1,2,-4,8,0,0,0,0

Notice there’s four zeros meaning the element has no data on it.

That was it for a dimensional array. Now let’s move to more than one dimension array.

For example there is a 2 dimension array.

Syntax 2D Array:
type name_array [row][col];

Example:

int a[3][4];

Next is string: is an array of characters  that ended with null character (”)

There types of string manipulation aka “things to do because you want to mess with words”. For example:

strlen()

Return a value of string length; excluded null char

strcpy(s1,s2)

Copy s2 to s1

strncpy(s1,s2,n)

Copy first n characters of s2 to s1

strcat(s1,s2)

Adding string s2 to the end of string s1

strncat(s1,s2,n)

Adding n characters of string s2 to the end of string s1

strcmp(s1,s2)

Comparing the value of string s1 and s2, if similar returning 0

–etc.

Well that’s about it. And like always, Thanks for reading