Tuesday, 30 October 2012

C Programming Structure and Pointer



Pointers can be accessed along with structures. A pointer variable of structure can be created as below:




struct name {
    member1;
    member2;
    .
    .
};
-------- Inside function -------
struct name *ptr;



Here, the pointer variable of type struct name is created.


Structure's member through pointer can be used in two ways:
  1. Referencing pointer to another address to access memory
  2. Using dynamic memory allocation
Consider an example to access structure's member through pointer.
#include <stdio.h>
struct name{
   int a;
   float b;
};
int main(){
    struct name *ptr,p;
    ptr=&p;            /* Referencing pointer to memory address of p */
    printf("Enter integer: ");
    scanf("%d",&(*ptr).a);
    printf("Enter number: ");
    scanf("%f",&(*ptr).b);
    printf("Displaying: ");
    printf("%d%f",(*ptr).a,(*ptr).b);
    return 0;
}
In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed.
Structure pointer member can also be accessed using -> operator.




(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b



Accessing structure member through pointer using dynamic memory allocation





To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file.



Syntax to use malloc()





ptr=(cast-type*)malloc(byte-size)



Example to use structure's member through pointer using malloc() function.







#include <stdio.h>
#include<stdlib.h>
struct name {
   int a;
   float b;
   char c[30];
};
int main(){
   struct name *ptr;
   int i,n;
   printf("Enter n: ");
   scanf("%d",&n);
   ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
   for(i=0;i<n;++i){
       printf("Enter string, integer and floating number  respectively:\n");
       scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
   }
   printf("Displaying Infromation:\n");
   for(i=0;i<n;++i)
       printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
   return 0;
}


Output



Enter n: 2
Enter string, integer and floating number  respectively:
Programming
2
3.2
Enter string, integer and floating number  respectively:
Structure
6
2.3
Displaying Information
Programming      2      3.20
Structure      6      2.30

Structures and Example Programs

Source: Here


C Programming Structure

Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.



Structure Definition in C




Keyword struct is used for creating a structure.



Syntax of structure




struct structure_name 
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};



We can create the structure for a person as mentioned above as:




struct person
{
    char name[50];
    int cit_no;
    float salary;
};


This declaration above creates the derived data type struct person.

Structure variable declaration



When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as:



struct person
{
    char name[50];
    int cit_no;
    float salary;
};

Inside main function:
struct person p1, p2, p[20];



Another way of creating sturcture variable is:






struct person
{
    char name[50];
    int cit_no;
    float salary;
}p1 ,p2 ,p[20];


In both cases, 2 variables p1p2 and array p having 20 elements of type struct person are created.

Accessing members of a structure




There are two types of operators used for accessing members of a structure.
  1. Member operator(.)
  2. Structure pointer operator(->) (will be discussed in structure and pointers chapter)
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:




p2.salary

Example of structure



Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot)





#include <stdio.h>
struct Distance{
    int feet;
    float inch;
}d1,d2,sum;
int main(){
    printf("1st distance\n");
    printf("Enter feet: ");
    scanf("%d",&d1.feet);  /* input of feet for structure variable d1 */
    printf("Enter inch: ");
    scanf("%f",&d1.inch);  /* input of inch for structure variable d1 */
    printf("2nd distance\n");
    printf("Enter feet: ");
    scanf("%d",&d2.feet);  /* input of feet for structure variable d2 */
    printf("Enter inch: ");
    scanf("%f",&d2.inch);  /* input of inch for structure variable d2 */
    sum.feet=d1.feet+d2.feet;
    sum.inch=d1.inch+d2.inch;
    if (sum.inch>12){  //If inch is greater than 12, changing it to feet.
        ++sum.feet;
        sum.inch=sum.inch-12;
    }
    printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); 
/* printing sum of distance d1 and d2 */
    return 0;
}


Output




1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances= 15'-5.7"

Keyword typedef while using structure




Programmer generally use typedef while using structure in C language. For example:




typedef struct complex{
  int imag;
  float real;
}comp;

Inside main:
comp c1,c2;


Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then, two structure variables c1 and c2 are created by this comp type.

Structures within structures


Structures can be nested within other structures in C programming.



struct complex
{
 int imag_value;
 float real_value;
};
struct number{
   struct complex c1;
   int real;
}n1,n2;


Suppose you want to access imag_value for n2 structure variable then, structure member n1.c1.imag_value is used.

Practical Program Examples on Arrays


Write a C program to find the average height of 'n' people where n is entered by user.
#include <stdio.h>
int main(){
    int height[100], n, i;
    float sum=0.0, average;
    printf("Enter the total number of person: ");
    scanf("%d",&n);
    while (n>100 || n<=0)
    {
        printf("Error! number should in range of (1 to 100).\n");
        printf("Please enter the number again.\n");
        scanf("%d",&n);
    }
   for(i=0;i<n;++i)
   {
      printf("%d. Enter height: ",i+1);
      scanf("%d",&height[i]);
      sum+=height[i];
   }
   average=sum/n;
   printf("Average height = %.2f",average);
   return 0;
}
Write a program to find largest element of an array.
#include <stdio.h>
int main(){
    int i;
    float arr[10];
    printf("Enter 10 elements to find largest among them: \n");
    for(i=0;i<10;++i)
    {
       printf("Enter Number %d: ",i+1);
       scanf("%f",&arr[i]);
    }
    for(i=1;i<10;++i)
    {
        if(arr[0]<arr[i])
            arr[0]=arr[i];
    }
    printf("Largest element = %.2f",arr[0]);
    return 0;
}
Write a C program to sort the array in ascending order.
#include <stdio.h>
int main(){
     int marks[100],n,i,step,temp;
     printf("Enter the number of students(should not be more than 100).\n");
     scanf("%d",&n);
     for(i=0;i<n;++i){
        printf("Enter marks%d:\n",i+1);
        scanf("%d",&marks[i]);
     }
     for(step=0;step<n-1;++step)
        for(i=0;i<n-step;++i)
        {
           if(marks[i]>marks[i+1])    
           {
              temp=marks[i];
              marks[i]=marks[i+1];
              marks[i+1]=temp;
           }
        }
     printf("In ascending order:\n");
     for(i=0;i<n;++i)
         printf("%d\t",marks[i]);
     return  0;
}
Write a C program to sort the array of 10 elements in descending order. To sort the data, make function Descend() to sort data in descending order and display the data in main() function.
#include <stdio.h>
void Descend(int c[]);
int main(){
   int c[10],i;
   for(i=0;i<10;++i){
     printf("Enter element %d:",i+1);
     scanf("%d",&c[i]);
   }
   Descend(c);
   printf("In descending order: ");
   for(i=0;i<10;++i){
       printf("%d\t",c[i]);
   }
   return 0;
}
Descend(int c[]){
    int i,j,temp;
    for(i=0;i<9;++i)
        for(j=i+1;j<10;++j)
        {
            if(c[i]<c[j]){
                temp=c[i];
                c[i]=c[j];
                c[j]=temp;
            }
        }
}
Write a C program to find the sum of two matrix entered by user using multidimensional arrays.
#include <stdio.h>
int main(){
    int r,c,a[100][100],b[100][100],sum[100][100],i,j;
    printf("Enter number of rows: ");
    scanf("%d",&r);
    printf("Enter number of columns: ");
    scanf("%d",&c);
    printf("Enter elements of 1st matrix");
    for(i=0;i<r;++i)
       for(j=0;j<c;++j)
       {
           printf("Enter a%d%d: ",i+1,j+1);
           scanf("%d",&a[i][j]);
       }
    printf("Enter elements of 2nd matrix");
    for(i=0;i<r;++i)
       for(j=0;j<c;++j)
       {
           printf("Enter a%d%d: ",i+1,j+1);
           scanf("%d",&b[i][j]);
       }
   for(i=0;i<r;++i)
       for(j=0;j<c;++j)
           sum[i][j]=a[i][j]+b[i][j];
    printf("Sum of two matrix is: \n\n");
    for(i=0;i<r;++i)
       for(j=0;j<c;++j)
       {
           printf("%d   ",sum[i][j]);
           if(j==c-1)
               printf("\n\n");
       }
return 0;
}
Write a C program to multiply two matrix. To perform this program,pass two matrix to separate function multiply() to multiply two matrix and display the output in main() function
#include <stdio.h>
void multiply(int a[][50],int b[][50],int c[][50],int r1,int c2,int c1);
int main(){
    int i,j,a[50][50],b[50][50],c[50][50],r1,c1,r2,c2;
    printf("For first matrix: Enter rows and column respectively.");
    scanf("%d%d",&r1,&c1);
    printf("For second matrix: Enter rows and column respectively.");
    scanf("%d%d",&r2,&c2);
    if(c1==r2)
    {
        for(i=0;i<r1;++i)
            for(j=0;j<c1;++j)
            {
                printf("Enter element a%d%d: ",i+1,j+1);
                scanf("%d",&a[i][j]);
            }
        for(i=0;i<r1;++i)
            for(j=0;j<c1;++j)
            {
                printf("Enter element b%d%d: ",i+1,j+1);
                scanf("%d",&b[i][j]);
            }
        multiply(a,b,c,r1,c2,c1);
        for(i=0;i<r1;++i)
            for(j=0;j<c2;++j)
            {
                printf("%d  ",c[i][j]);
                if(j==c2-1)
                   printf("\n");
            }
    }
    else
       printf("Error! column of 1st matrix not equal to row of 2nd");
    return 0;
}
void multiply(int a[][50],int b[][50],int c[][50],int r1,int c2,int c1){
    int i,j,k;
    for(i=0;i<r1;++i)
         for(j=0;j<c2;++j)
               c[i][j]=0;
    for(i=0;i<r1;++i)
         for(j=0;j<c2;++j)
            for(k=0;k<c1;++k)
                 c[i][j]+=a[i][k]*b[k][j];

}

Passing arrays to a function


C Programming Arrays and Functions

In C programming, a single array element or an entire array can be passed to a function. Also, both one-dimensional and multi-dimensional array can be passed to function as argument.


Passing One-dimensional Array In Function



C program to pass a single element of an array to function




#include <stdio.h>
void display(int a)
   {
   printf("%d",a);
   }
int main(){
   int c[]={2,3,4};
   display(c[2]);  //Passing array element c[2] only.
   return 0;
}





4


Output

Single element of an array can be passed in similar manner as passing variable to a function.

Passing entire one-dimensional array to a function


While passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting address of memory area is passed as argument).


Write a C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function.





#include <stdio.h>
float average(float a[]);
int main(){
     float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
     avg=average(c);   /* Only name of array is passed as argument. */
     printf("Average age=%.2f",avg);
     return 0;
   }
float average(float a[]){ 
     int i;
     float avg, sum=0.0;
     for(i=0;i<6;++i){
       sum+=a[i];
     }
     avg =(sum/6);
     return avg;
}


Output




Average age=27.08

Passing Multi-dimensional Arrays to Function



To pass two-dimensional array to a function as an argument, starting address of memory area reserved is passed as in one dimensional array

Example to pass two-dimensional arrays to function





#include 
void Function(int c[2][2]);
int main(){
   int c[2][2],i,j;
   printf("Enter 4 numbers:\n");
   for(i=0;i<2;++i)
      for(j=0;j<2;++j){
           scanf("%d",&c[i][j]);
      }
   Function(c);   /* passing multi-dimensional array to function */
   return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */
   int i,j;
   printf("Displaying:\n");
   for(i=0;i<2;++i)
      for(j=0;j<2;++j)
          printf("%d\n",c[i][j]);
}




Output






Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

Monday, 29 October 2012

Functions: Passing Value and Pass Reference

Pass by value and pass by reference (and reference variables)

Pass by value and Pass by Reference

We have seen as to how to pass values to a function through arguments. Actually there are two ways to pass values to a function through arguments. These two methods are explained below with examples.
Pass By Value:
Example:
void check (int x)
{
//body of function
}
int main ( )
{
int b = 10;
check (b);
}

In this function, ‘x’ is a parameter and ‘b’ (which is the value to be passed) is the argument. In this case the value of ‘b’ (the argument) is copied in ‘x’ (the parameter). Hence the parameter is actually a copy of the argument. The function will operate only on the copy and not on the original argument. This method is known as PASS BY VALUE. So far we have dealt only with pass by value (except when passing arrays to functions).
// Pass by value illustration
#include <iostream.h>
int square (int x)
{
return x*x;
}
int main ( )
{
int num = 10;
int answer;
answer = square(num);
cout<<"Answer is "<<answer; // answer is 100
cout<<" Value of a is "<<num; // num will be 10
return 0;
}

You can see that the value of ‘num’ is unchanged. The function ‘square’ works only on the parameter (i.e. on x ). It does not work on the original variable that was passed (i.e it doesn't work on ‘num’).
The diagram makes it quite clear as to what happens when we call square(num). The following initialization takes place:
            int x = num;
and the function square( ) operates only on a copy of num.

Pass By Reference

In pass by reference method, the function will operate on the original variable itself. It doesn't work on a copy of the argument but works on the argument itself. Consider the same square function example:
// Illustration of pass by reference
#include <iostream.h>
void square (int *x)
{
*x = (*x) * (*x);
}

int main ( )
{
int num = 10;
square(&num);
cout<<" Value of num is "<<num; // Value of num is 100
return 0;
}

As you can see the result will be that the value of a is 100. The idea is simple: the argument passed is the address of the variable ‘num’. The parameter of ‘square’ function is a pointer pointing to type integer. The address of ‘num’ is assigned to this pointer. You can analyze it as follows: &num is passed to int *x, therefore it is the same as:
int *x = &num;
This means that ‘x’ is a pointer to an integer and has the address of the variable num.
Within the function we have:

*x = (*x) * (*x);

* when used before a pointer will give the value stored at that particular address. Hence we find the product of ‘num’ and store it in ‘num’ itself. i.e. the value of 100 is stored in the address of ‘num’ instead of 10 which was originally present there. The diagram below illustrates the difference between pass by value and pass by reference. Now when we dereference ‘x’ we are actually manipulating the value stored in ‘num’.
This is the pass-by-reference method which was used in C. In C++ there is a different approach. Of course you can use the above method, but C++ has its own special way.




aliases: Pass by value

From clc-wiki

Pass by value is a term describing function call semantics. To pass by value means that the argument (a variable, constant or other expression) is evaluated and a copy of its value is then passed to the function.
Whenever the function accesses the parameter it receives, it does so without reference to the original argument which cannot be overwritten; nor can a volatile argument change the value of the parameter once the function is entered. Pass by value semantics can be contrasted with pass by reference semantics, which C does not directly support.

Quick examples

The program below
#include <stdio.h>
void foo(int x);

int main(void) {
  int i = 5;
  
  printf("In main(): %d\n", i);
  foo(i);
  printf("In main(): %d\n", i);

  return 0;
}

void foo(int x) {
  printf("In foo(): %d\n", x);
  x = 10;
  printf("In foo(): %d\n", x);
}
prints
 In main(): 5
 In foo(): 5
 In foo(): 10
 In main(): 5







From clc-wiki

Pass by reference is a term that describes a part of the semantics of function parameters. To pass by reference means that within the function, the formal parameter is or acts as an alias (reference) for the function argument - so pass by reference is only meaningful when the function's argument is a variable (note that "parameter" and "argument" have slightly different meanings - consult the link in the "See Also" section below).
Within the function, accesses of the formal parameter, either for reading or for writing, directly access the same variable that the caller of the function passed in as its argument.
C does not directly support pass by reference because it always uses pass by value, but a programmer can implement pass by reference by passing a pointer to the variable that the programmer wants passed by reference.

Quick examples

The program below
#include <stdio.h>
void foo(int *x);

int main(void) {
  int i = 5;
  
  printf("In main(): %d\n", i);
  foo(&i);
  printf("In main(): %d\n", i);

  return 0;
}

void foo(int *x) {
  printf("In foo(): %d\n", *x);
  *x = 10;
  printf("In foo(): %d\n", *x);
}
prints
 In main(): 5
 In foo(): 5
 In foo(): 10
 In main(): 10

Notes on proper usage

Pass by reference and call by reference are synonyms and are specific terms of art that indicate direct syntactical support in the language. Referring to the C mechanism used in the example above - passing a pointer to a variable in order to access the variable within the function - as "pass by reference" is technically incorrect. This is because within the function the language's syntax requires the dereferencing operator to be applied to the pointer, whereas true pass by reference, such as supported by Pascal (parameters declared with var) and C++ (parameters declared with &), does not have that requirement. Better and more correct is to refer to the C mechanism as "passing a reference".




Pass values using function parameters
The first is to pass data into the function using input parameters, as we looked at a few sessions back. Our program would look something like this:-
main()
{                                 |
  float f,res;                    | this is the scope of the f variable
  scanf("%f",&f);                 |
  res = one_over(f);              |
  printf(" res is %3.2f", res );  |
}
 
float one_over(float amt)
{
  float j;                 |
  if (amt==0) amt==1;      | this is the scope of the j variable
  j = 1 / amt;             | and the amt parameter variable
  return j;                |
}
We can see that we are passing the i variable into the one_over function. This gets copied into the amt local variable inside the function. This can then be changed if necessary (as it is here to ensure that we never divide by zero, although this is not a very good solution to the problem!).
The  result is then returned from the function (of type float as specified at the start of the function's definition line and prototype line), which has been calculated to be one divided by the original value.
Control is passed back to the original program, where one_over(f) is replaced with the return value - e.g. if f contained 2 then the value returned would be 1/2 (i.e. 1 divided by 2) - i.e. 0.5, so one_over(f) is replaced with 0.5, and the line in main() becomes res = 0.5. So res gets filled with the value 0.5 in this example.
Pass values using global variables
Another method, which is generally frowned upon by many, is to use variables that are available to every function in your program. These are called global variables.
To declare a global variable and make it available to all functions, just to the definition out of a specific function, and put it towards the top of your program - just above the main() function should be fine.  This implies that the scope of the variable has changed to be outside all functions, and therefore available to all functions. Our program can now look like this:-
float f,res;
 
main()                                              |
{                                                   |
  scanf("%f",&f);                                   |
  one_over;                                         | this is the scope 
  printf(" res is %3.2f", res );                    | of the res and f variables
}                                                   |
                                                    |
void one_over;                                      |
{                                                   |
  float amt;               |                        |
  amt = f;                 | this is the scope      |
  if (amt==0) amt==1;      | of the amt variable    |
  res = 1 / amt;           |                        |
}                                                   |
In this case, we have placed both the input (variable f) and output (variable res) as global variables. By doing so, we must always make sure we set variable f before we call the one_over function, as it is now providing the input.  We must also make sure that the variables res is set before the function ends, as this is now providing the output.
It would be possible to provide input as shown in the previous section, by passing a parameter, and providing the ouput as the res variable, and then we could keep the res variable local to the main() function.  This would mean that we could re-use the one_over function in different functions without the fear of overwriting the result.
We still run the risk of losing our input, if the one_over function is used in several different places - we risk mixing the inputs and outputs up of if we use it several different times. This is the advantage of keeping variables local, and passing parameters - this keeps the risk of overwriting something unintentionally to a minimum, and is the reason why you should not use global variables unless really necessary.
A typical example of where it would be okay to use a global variable might be a variable that is truly only ever used for one purpose throughout a program - for example score or high_score in a game, or userid in a password-protected application.



MORE EXAMPLES:

Pointer

Passing by pointer is where you pass a function a pointer to the object you want worked with. You are not actually changing the object itself, just the local or temporary copy that you have made with the pointer.

This code is wrong. Both output 10 and I can not for the life of me figure out why that is. Perhaps I am using pointers wrong.

Code:


#include <iostream>
 
int foo(int *bar)
{
    *bar = (*bar + *bar);
     
    return(*bar);
}
 
int main()
{
    int baz = 5;
    int *pbaz = &baz;
 
    std::cout << foo(pbaz); // Should equal 10
    std::cout << "\n" << baz; // Should equal 5
 
    std::cin.get();
    return(0);
}


Reference

Passing by reference means that you don't pass the value of an object, you are passing the object itself. There are no copies made, only the original object is what is worked with.

Code:
 
 
#include <iostream>
 
int foo(int &bar)
{
    bar = (bar + bar);
     
    return(bar);
}
 
int main()
{
    int baz = 5;
 
    std::cout << foo(baz); // Should equal 10
    std::cout << "\n" << baz; // Should equal 10
 
    std::cin.get();
    return(0);
}
 
 
 
 
Value

Passing by value means that you are taking a copy of what has been passed to the function, work with it in the function, but do not modify the original value.

Code:
 
 
#include <iostream>
 
int foo(int bar)
{
    bar = (bar + bar);
     
    return(bar);
}
 
int main()
{
    int baz = 5;
 
    std::cout << foo(baz); // Should equal 10
    std::cout << "\n" << baz; // Should equal 5
 
    std::cin.get();
    return(0);
}
 
 


References:

http://www.simonhuggins.com/courses/cbasics/course_notes/session19.htm