Saturday, 13 August 2011

Structured Datatypes

  • A structure in C is a collection of items of different types. You can think of a structure as a "record" is in Pascal or a class in Java without methods.
  • Structures, or structs, are very useful in creating data structures larger and more complex than the ones we have discussed so far.
  • Simply you can group various built-in data types into a structure.
  • Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex.
Following is the example how to define a structure.
struct student {
    char firstName[20];
    char lastName[20];
    char SSN[9];
    float gpa;
  };
Now you have a new datatype called student and you can use this datatype define your variables of student type:
struct student student_a, student_b;

or an array of students as

struct student students[50];
Another way to declare the same thing is:
struct {
    char firstName[20];
    char lastName[20];
    char SSN[10];
    float gpa;
  } student_a, student_b;
All the variables inside an structure will be accessed using these values as student_a.firstName will give value of firstName variable. Similarly we can aqccess other variables.

Structure Example:

Try out following example to understand the concept:
#include <stdio.h>
struct student {
    char firstName[20];
    char lastName[20];
    char SSN[10];
    float gpa;
};

main()
{
  struct student student_a;

  strcpy(student_a.firstName, "Deo");
  strcpy(student_a.lastName, "Dum");
  strcpy(student_a.SSN, "2333234" );
  student_a.gpa = 2009.20;

 printf( "First Name: %s\n", student_a.firstName );
 printf( "Last Name: %s\n", student_a.lastName );
 printf( "SNN : %s\n", student_a.SSN );
 printf( "GPA : %f\n", student_a.gpa );
 
This will produce following results:
First Name: Deo Last Name: Dum SSN : 2333234 GPA : 2009.20


Pointers to Structs:

Sometimes it is useful to assign pointers to structures (this will be evident in the next section with self-referential structures). Declaring pointers to structures is basically the same as declaring a normal pointer:
struct student *student_a;
To dereference, you can use the infix operator: ->.
printf("%s\n", student_a->SSN); 
 

typedef Keyword

There is an easier way to define structs or you could "alias" types you create. For example:
typedef struct{
    char firstName[20];
    char lastName[20];
    char SSN[10];
    float gpa;
  }student;
Now you can use student directly to define variables of student type without using struct keyword. Following is the example:
student student_a;
You can use typedef for non-structs:
typedef long int *pint32;

pint32 x, y, z;
x, y and z are all pointers to long ints

Unions Datatype

Unions are declared in the same fashion as structs, but have a fundamental difference. Only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location.
Here is how we define a Union
union Shape {
      int circle;
      int triangle;
      int ovel;
};
We use union in such case where only one condition will be applied and only one variable will be used.

  • You can create arrays of structs.
  • Structs can be copied or assigned.
  • The & operator may be used with structs to show addresses.
  • Structs can be passed into functions. Structs can also be returned from functions.
  • Structs cannot be compared!
  • Structures can store non-homogenous data types into a single collection, much like an array does for common data (except it isn't accessed in the same manner).
  • Pointers to structs have a special infix operator: -> for dereferencing the pointer.
  • typedef can help you clear your code up and can help save some keystrokes.


 

 

String Functions

  • In C language Strings are defined as an array of characters or a pointer to a portion of memory containing ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL '\0' character:
     Strings are arrays of chars. String literals are words surrounded by double quotation marks.

To declare a string of 49 letters, you would want to say:
char string[50];
  • It is important to preserve the NULL terminating character as it is how C defines and manages variable length strings. All the C standard library functions require this for successful operation.
char *arry; Can also be used as a string.
arry = new char[256];
 
which allows you to access arry just as if it were an array. Keep in mind that to use delete you must put [] between delete and arry to tell it to free all 256 bytes of memory allocated.
delete [] arry.
 
  • All the string handling functions are prototyped in: string.h or stdio.h standard header file. So while using any string related function, don't forget to include either stdio.h or string.h. May be your compiler differes so please check before going ahead.
  • If you were to have an array of characters WITHOUT the null character as the last element, you'd have an ordinary character array, rather than a string constant.
  • String constants have double quote marks around them, and can be assigned to char pointers as shown below. Alternatively, you can assign a string constant to a char array - either with no size specified, or you can specify a size, but don't forget to leave a space for the null character!
char *string_1 = "Hello";
char string_2[] = "Hello";
char string_3[6] = "Hello";

Reading and Writing Strings:

One possible way to read in a string is by using scanf. However, the problem with this, is that if you were to enter a string which contains one or more spaces, scanf would finish reading when it reaches a space, or if return is pressed. As a result, the string would get cut off. So we could use the gets function
A gets takes just one argument - a char pointer, or the name of a char array, but don't forget to declare the array / pointer variable first! What's more, is that it automatically prints out a newline character, making the output a little neater.
A puts function is similar to gets function in the way that it takes one argument - a char pointer. This also automatically adds a newline character after printing out the string. Sometimes this can be a disadvantage, so printf could be used instead.
#include <stdio.h>

int main() {
  char array1[50];
  char *array2;

  printf("Now enter another string less than 50");
  printf(" characters with spaces: \n");
  gets(array1);

  printf("\nYou entered: ");
  puts(array1);

  printf("\nTry entering a string less than 50");
  printf(" characters, with spaces: \n");
  scanf("%s", array2);

  printf("\nYou entered: %s\n", array2);

  return 0;
}
This will produce following result:
Now enter another string less than 50 characters with spaces:
hello world

You entered: hello world

Try entering a string less than 50 characters, with spaces:
hello world

You entered: hello 

String Manipulation Functions

Functions

A function is a module or block of program code which deals with a particular task. Making functions is a way of isolating one block of code from other independent blocks of code.
Functions serve two purposes.
  • They allow a programmer to say: `this piece of code does a specific job which stands by itself and should not be mixed up with anyting else',
  • Second they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text.
A function can take a number of parameters, do required processing and then return a value. There may be a function which does not return any value.
You already have seen couple of built-in functions like printf(); Similar way you can define your own functions in C language.
Consider the following chunk of code
int total = 10;
   printf("Hello World");
   total = total + l;
To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single compound statement and write the name that you want to give it in front of the brackets:
Demo()
{
   int total = 10;
   printf("Hello World");
   total = total + l;
}
curved brackets after the function's name are required. You can pass one or more paramenters to a function as follows:
Demo( int par1, int par2)
{
   int total = 10;
   printf("Hello World");
   total = total + l;
}
By default function does not return anything. But you can make a function to return any value as follows:
int Demo( int par1, int par2)
{
   int total = 10;
   printf("Hello World");
   total = total + l;

   return total;
}
 

Passing Parameters to a Function

There are two ways to pass parameters to a function:
  • Pass by Value: mechanism is used when you don't want to change the value of passed paramters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables.
  • Pass by Reference mechanism is used when you want a function to do the changes in passed parameters and reflect those changes back to the calling function. In this case only addresses of the variables are passed to a function so that function can work directly over the addresses.
Here are two programs to understand the difference: First example is for Pass by value:
#include <stdio.h>

/* function declaration goes here.*/
void swap( int p1, int p2 );

int main()
{
   int a = 10;
   int b = 20;

   printf("Before: Value of a = %d and value of b = %d\n", a, b );
   swap( a, b );
   printf("After: Value of a = %d and value of b = %d\n", a, b );
}

void swap( int p1, int p2 )
{
    int t;

    t = p2;
    p2 = p1;
    p1 = t;
   printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Here is the result produced by the above example. Here the values of a and b remain unchanged before calling swap function and after calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 10 and value of b = 20
Following is the example which demonstrate the concept of pass by reference
#include <stdio.h>

/* function declaration goes here.*/
void swap( int *p1, int *p2 );

int main()
{
   int a = 10;
   int b = 20;

   printf("Before: Value of a = %d and value of b = %d\n", a, b );
   swap( &a, &b );
   printf("After: Value of a = %d and value of b = %d\n", a, b );
}

void swap( int *p1, int *p2 )
{
    int t;

    t = *p2;
    *p2 = *p1;
    *p1 = t;
   printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
Here is the result produced by the above example. Here the values of a and b are changes after calling swap function.
Before: Value of a = 10 and value of b = 20 Value of a (p1) = 20 and value of b(p2) = 10 After: Value of a = 20 and value of b = 10

Pointing to Data

A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier.
  • There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators.
  • When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer vairable.
  • When you place an asterisk in front of a pointer you will get the value at the memory address pointed to.
Here is an example to understand what I have stated above.

#include <stdio.h>

int main()
{
  int my_variable = 6, other_variable = 10;
  int *my_pointer;

  printf("the address of my_variable is    : %p\n", &my_variable);
  printf("the address of other_variable is : %p\n", &other_variable);

  my_pointer = &my_variable;

  printf("\nafter \"my_pointer = &my_variable\":\n");
  printf("\tthe value of my_pointer is %p\n", my_pointer);
  printf("\tthe value at that address is %d\n", *my_pointer);

  my_pointer = &other_variable;

  printf("\nafter \"my_pointer = &other_variable\":\n");
  printf("\tthe value of my_pointer is %p\n", my_pointer);
  printf("\tthe value at that address is %d\n", *my_pointer);

  return 0;
}

This will produce following result.

the address of my_variable is    : 0xbfffdac4
the address of other_variable is : 0xbfffdac0

after "my_pointer = &my_variable":
        the value of my_pointer is 0xbfffdac4
        the value at that address is 6

after "my_pointer = &other_variable":
        the value of my_pointer is 0xbfffdac0
        the value at that address is 10 
 

Pointers and Arrays

The most frequent use of pointers in C is for walking efficiently along arrays. In fact, in the implementation of an array, the array name represents the address of the zeroth element of the array, so you can't use it on the left side of an expression. For example:
char *y;
   char x[100];
y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an element of x by either of
y = &x[0];
   y = x;
Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the following:
*(y+1) gives x[1] *(y+i) gives x[i] and the sequence y = &x[0]; y++; leaves y pointing at x[1].



Pointer Arithmetic:

C is one of the few languages that allows pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For example:
int x = 5, *ip = &x;

  ip++;
On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it.
Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C.


Generic Pointers: ( void Pointer )

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer. This is very useful when you want a pointer to point to data of different types at different times.
Try the following code to understand Generic Pointers.
#include <stdio.h>

int main()
{
  int i;
  char c;
  void *the_data;

  i = 6;
  c = 'a';

  the_data = &i;
  printf("the_data points to the integer value %d\n", 
                         *(int*) the_data);

  the_data = &c;
  printf("the_data now points to the character %c\n", 
                         *(char*) the_data);

  return 0;
}
NOTE-1 : Here in first print statement, the_data is prefixed by *(int*). This is called type casting in C language.Type is used to caste a variable from one data type to another datatype to make it compatible to the lvalue.
NOTE-2 : lvalue is something which is used to left side of a statement and in which we can assign some value. A constant can't be an lvalue because we can not assign any value in contact. For example x = y, here x is lvalue and y is rvalue.
However, above example will produce following result:



 
 

What is Operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. C language supports following type of operators.
  • Arithmetic Operators
  • Logical (or Relational) Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators
Lets have a look on all operators one by one.

Arithmetic Operators:

There are following arithmetic operators supported by C language:
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
OperatorDescriptionExample
+Adds two operands A + B will give 30
-Subtracts second operand from the first A - B will give -10
*Multiply both operands A * B will give 200
/Divide numerator by denumerator B / A will give 2
%Modulus Operator and remainder of after an integer division B % A will give 0
++Increment operator, increases integer value by one A++ will give 11
--Decrement operator, decreases integer value by one A-- will give 9

Logical (or Relational) Operators:

There are following logical operators supported by C language
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
OperatorDescriptionExample
== Checks if the value of two operands is equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands is equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (A && B) is true.
||Called Logical OR Operator. If any of the two operands is non zero then then condition becomes true. (A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
Show Examples
There are following Bitwise operators supported by C language
OperatorDescriptionExample
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in eather operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~A ) will give -60 which is 1100 0011
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111

Assignment Operators:

There are following assignment operators supported by C language:
Show Examples
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assigne value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
<<=Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>=Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operator C &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.
So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

Misc Operators

There are few other operators supported by C Language.
Show Examples
OperatorDescriptionExample
sizeof()Returns the size of an variable. sizeof(a), where a is interger, will return 4.
&Returns the address of an variable.&a; will give actaul address of the variable.
*Pointer to a variable.*a; will pointer to a variable.
? :Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Operators Categories:

All the operators we have discussed above can be categorised into following categories:
  • Postfix operators, which follow a single operand.
  • Unary prefix operators, which precede a single operand.
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
  • Assignment operators, which assign a value to a variable.
  • The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.
Category  Operator  Associativity 
Postfix  () [] -> . ++ - -   Left to right 
Unary  + - ! ~ ++ - - (type) * & sizeof  Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   << >>  Left to right 
Relational   < <= > >=  Left to right 
Equality   == !=  Left to right 
Bitwise AND  &  Left to right 
Bitwise XOR  ^  Left to right 
Bitwise OR  |  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 
Comma  ,  Left to right 

Constants

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
  • Octal constants are written with a leading zero - 015.
  • Hexadecimal constants are written with a leading 0x - 0x1ae.
  • Long constants are written with a trailing L - 890L.
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows.
'\n'	newline
'\t'	tab
'\\'	backslash
'\''	single quote
'\0'	null ( Usedautomatically to terminate character string )
In addition, a required bit pattern can be specified using its octal equivalent.
'\044' produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator.
A character is a different type to a single character string. This is important poing to note.

Defining Constants

ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed.
The const keyword is to declare a constant, as shown below:
int const a = 1;
const int a =2;
Note:
  • You can declare the const before or after the type. Choose one an stick to it.
  • It is usual to initialise a const with a value as it cannot get a value any other way.
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants in a program.
#define TRUE		1
#define	FALSE		0
#define NAME_SIZE	20
Here TRUE, FALSE and NAME_SIZE are constant
You frequently see const declaration in function parameters. This says simply that the function is not going to change the value of the parameter.
The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completenes of this section it is is included here:
void strcpy(char *buffer, char const *string)

The enum Data type

enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here's an example:
enum colors {RED, YELLOW, GREEN, BLUE};
I've made the constant names uppercase, but you can name them which ever way you want.
Here, colors is the name given to the set of constants - the name is optional. Now, if you don't assign a value to a constant, the default value for the first one in the list - RED in our case, has the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1, GREEN is 2 and BLUE is 3.
But you can assign values if you wanted to:
enum colors {RED=1, YELLOW, GREEN=6, BLUE };
Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.
The main advantage of enum is that if you don't initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards.
You can name your constants in a weird order if you really wanted...
#include <stdio.h>

int main() {
  enum {RED=5, YELLOW, GREEN=4, BLUE};

  printf("RED = %d\n", RED);
  printf("YELLOW = %d\n", YELLOW);
  printf("GREEN = %d\n", GREEN);
  printf("BLUE = %d\n", BLUE);
  return 0;
}

This will produce following results

  RED = 5
  YELLOW = 6
  GREEN = 4
  BLUE = 5

Input / Output

input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement.
Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data

printf() function

This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. ).

Try following program to understand printf() function.
#include <stdio.h>

main()
{
  int dec = 5;
  char str[] = "abc";
  char ch = 's';
  float pi = 3.14;

  printf("%d %s %f %c\n", dec, str, pi,  ch);
}
The output of the above would be:
5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character.


scanf() function

This is the function which can be used to to read an input from the command line.
Try following program to understand scanf() function.
#include <stdio.h>

main()
{
  int x;
  int args;

  printf("Enter an integer: ");
  if (( args = scanf("%d", &x)) == 0) {
      printf("Error: not an integer\n");
  } else {
      printf("Read in %d\n", x);
  }
}
Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x.
This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message.
Enter an integer: 20
Read in 20
.