সোমবার, ১৮ অক্টোবর, ২০১০

37. Structures

The structure mechanism allows us to aggregate variables of different types
struct definitions are usually placed outside of functions so that they are in scope throughout the file, as in the following example:

The “.” in a.num is the “structure member operator”, which connects the structure name and the member name.
A “member” is a variable in a structure.
Assignment (=) works just as you would expect, as if there were a separate assignment for each structure member.

Structures Simple Example

struct card_struct {
int number;
char suit;
}; /* note the semicolon after the definition! */
void some_function() {
struct card_struct a, b;
a.number = 3;
a.suit = ’D’;
b = a;
}

Structure member as Parameter

void sum(double p1_x,double p1_y,double p2_x,double p2_y ) {
struct point psum;
psum.x = p1_x + p2_x;
psum.y = p1_y + p2_y;
printf(“%lf_%lf\n”, psum.x, psum.y); 10_5
}
void main()
 {
struct point a, b, c;
a.x = 3.5; a.y = 4.5; b.x = 6.5; b.y = 0.5;
printf(“%lf_%lf_%lf_%lf\n”, a.x, a.y, b.x, b.y);
sum( a.x, a.y, b.x, b.y); 3.5_4.5_6.5_0.5
}

Structure as Parameter

Structures work seamlessly with functions.
A structure is a type, so it can be the type of a function parameter (as here), or a return type:
point sum( struct point p1, struct point p2 ) {
struct point psum;
psum.x = p1.x + p2.x;
psum.y = p1.y + p2.y;
return psum;
}
void main() { 3.5_4.5_6.5_0.5_10_5
struct point a, b, c;
a.x = 3.5; a.y = 4.5; b.x = 6.5; b.y = 0.5;
c = sum( a, b);
printf(“%lf_%lf_%lf_%lf_%lf_%lf\n”, a.x, a.y, b.x, b.y, c.x, c.y);
}

Post by j.siam,
Ref-: Md Munirul Haque

36. Strings


When dealing with strings in C, you should always think of the underlying array of characters.
Also: always think in terms of the activation records! You must explicitly allocate all the space for every string you use.


String Example


void main()
{
char s[] = "Hi!"; // initialization with string constant
char s2[] = { 'H' , 'i' , '!' , '\0' };
// initialization with char constant
int i;
for( i = 0; s[i] != 0; i++ )
printf( "%c_%c_", s[i], s2[i] );




}


Output: H_H_i_i_!_!_



String input


Alternative way of taking string input


char str[80];
scanf(“%s”, str);
scanf(“%s”, &str[0]);
gets(str);
for(i=0; i<10;i++)
scanf(“%c”, &str[i]);

String handling functions These are from string.h library. (You have to #include to use these functions).
int strlen( char *s ); Returns the length of the string s.
strlen(“hello”) will return the value 5
char *strcat( char *s1, char *s2 ); Takes two strings as arguments, concatenates them, and puts the result in s1.
The programmer must ensure that s1 points to enough space to hold the result. The string s1 is returned.
strcat(“hello”, “_world”) will return string “hello_world”



char *strcpy( char *s1, char *s2 );
The string s2 is copied into s1.
Whatever exists in s1 is overwritten. It is assumed that s1 has enough space to hold the result. The value of s1 is returned.
strcpy(s1, s2) will return s1 with the new value copied from s2


(Remember, using = to assign one string to another only copies pointers, it doesn’t actually give a new copy of the string. And it won’t work at all if the left hand side is a string array.)


int strcmp( char *s1, char *s2 ); Integer is returned that is less than, equal to, or greater than zero, depending on whether s1 is lexicographically less than, equal to, or greater than s2 (respectively).


strcmp(“he”, “hi”) will return less than 0
strcmp(“12”, “12”) will return 0
strcmp(“they”, “the”) will return greater than 0

Post by j.siam,
Ref-: Md Munirul Haque

35. Introduction to Pointer and Arrays

Pointer and arrays:
1. Array elements are always stored in contiguous memory location.
2. A pointer when incremental always pointer to an immediately next location of its type.
Suppose we have an array,
int mamun[ ]={3,4,5,6};
Suppose the elements are located in memory as
Elements:               3        4           5           6
Memory location: 1000   1002      1004      1005
Here is program that prints out the memory location in which the elements of this array are stored.

main( )
{
   int mamun[ ]={3,4,5,6};
   int i=0,*p;
   p=mamun;   /*Because the array name is a base address of first elemnt of the array. We cam also write it p=mamunb[0]*/
     while (i<=4)
 {
    printf(" \n Address = %u",&mamun[i]);
    printf("\n Element = %d", *p);
    i++;
    p++;
 }
}
output:
address             elements
1000                  3
1002                  4
1004                  5
1006                  6

in this program, to begin with  we have collected the base address of the array(address of 0th  element) in the variable p using the statement,
p=mamun; /*assigns address 1000to p*/.
When we are inside the loop for the first time p contains the address 1000,and the value at this address is 24.
These continue till the last element of the array has bee n printed.

A word of caution! D o not attempt the following operations on pointer ... they would never work out.
1. Addition of two pointers.
2. Multiplying a pointer with a number.
3. Dividing a pointer with a number. 

written by mamun

34. Pointer and Functions

Passing addresses to Functions:

Look at this porgram

#include<stdio.h>
void arnob(int,int)
main( )
{
int a=10,b=20;
arnob(&a,&b);
printf("\na=%d",a);
printf("\nb=%d",b);
}

arnob(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

The output of the above program would be:
a=20
b=10

  When we send the address of  a and b it come in the function arnob. But we know that the normal variable can not store the address of a variable. So if we want to store the address of a and b we mast declere the pointer type variable. Because we know that only pointer type variable can store the address of a variable. So in the function arnob we declear two pointer x and y to store the address of a and b. And we also declear a normal variable t. Now we put the value of *x in t. Also we know that *x mean 'value at address x' that means  a. And we know a=10. So t=*x mean that t=a i mean t=10. Now *x=*y mean that a=b. So tha valu of a is now 20. *y=t, we know that the valu of t=10. So *y=t mean b=10. Look at this porgram we work in tha fanction arnob. But the value of a and b change in the main function.

post by Arnob

33. Pointer Expressions

Let us now see what are pointers and how they can be used in various expressions. If i=5 then expression &i returns the adderss of i. If we so desire, this address can be collected in avariable by saying,

j=&i;

But remember that j is not an ordinary variable like any other integer variable. It is a variable, which contains the address of another variable. Since j is a variable the compiler ust probide it space in memory. Once again, the following memory map would illustrate the contents of and j.

As you can see, i's value is 5 and j's value is i's address.

But wait, we can't use j in program without declaring it. And since j is a variable, which contains the address of i, it is declared as,

int *j;

This declaration tells the conpiler that j will be used to store the address of an integer value - in other words j points to an integer. How do we justify the usage of  * (pointer).

int *j;

Let us go by the meaning of *. It stand for 'value at address'. Thus, int *j would mean, the value at the address contained in j is an int.

Look at the following declarations,

int *alpha;
char *ch;
float *s;

Here, alpha, ch and s are declared as pointer variables, i.e. variables capable of holding addresses. Remember that, addresses are always going to be whole numbers, therefore pointers always contain whole numbers. The declaration float *s does not mean that s is going to contain a floating-point value. What it means is, s is going to contain the address of a floating-point value. Similarly, char *ch means that ch is going to contain the address of a char value.

Pointer we know is a variable, which contains address of another variable. Now this variable itself could be another pointer. Thus, we now have a pointer, which contains another pointer's address. The following example should make this point clear.

#include<stdio.h>
main( )
{
int i=5;
int *j;
int **k;

j=&i;
k=&j;
printf(" \n Address of i = %u",&i);
printf(" \n Address of i = %u",j);
printf(" \n Address of i = %u",*k);
printf(" \n Address of j = %u",&j);
printf(" \n Address of j = %u",k);
printf(" \n Address of k = %u",&k);

printf("\n\n Value of j = %u",j);
printf("\n Value of k = %u",k);
printf("\n Value of i = %d",i);
printf("\n Value of i = %d",*(&i));
printf("\n Value of i = %d",*j);
printf("\n Value of i = %d",**k);
getch();
}

The output of the above program would be:

Address of i = 6589
Address of i = 6589
Address of i = 6589
Address of j = 3275
Address of j = 3275
Address of k = 7234

Value of j = 6589
Value of k = 3275
Value of i = 5
Value of i = 5
Value of i = 5
Value of i = 5

The following memory map would help you in tracing out how the program prints the above output.
Observe how the variables i, j and k have been declared,

int i;
int *j;
int **k;

Here, i is an ordinary int, j is a pointer to an int, whereas k is a pointer to a pointer. In principle, there could be a pointer to a pointer to a pointer, or a pointer to a pointer to a pointer/ There is no limit on how far can we go on extending this definition.

Taken from 'Understanding Pointers In C'
post by Arnob

32.The & and * Operators in POINTER

Consider the declaration,

int i=5;

This declaration tells the C compier to

  • Reserve space in memory to hold the integer value.
  • Associate the name i with this memory location.
  • Store the value 3 at this location.
We may represent i's location in the memory by the following memory map:

we see that the computer has selected memory location 6589 as the place to store the value 5. This location number 6589 is not a number to be relied upon, becuse some othertime the computer may choose a different location for storring the value 5. The important point is, i's address in memory is a number.

We can print this adderss through the following program:

#include<stdio.h>
main( )
{
int i=5;
printf("\n Address of i=%u", &i);
printf("\n Value of i=%u", i);
getch();
}

The output of the above program would be:

Address of i=6589
Value of i=5

Now look at the first printf( ) statement carefully. The '&' operator used in this statement is C's 'address of' operator. The expression &i returns the address of the variable i, which in this case happens to be 6589.

The other pointer operator available in Cis '*', called 'value at address' operator. It returns the value stored at a porticular address. The 'value at address' operator is also called an 'indirection' operator.

post by Arnob.
taken from 'Understanding pointers In C' 

রবিবার, ১৭ অক্টোবর, ২০১০

31. Introduction to Pointers

Introduction to Pointers
 Pointer is new type of variable that holds the memory address of another variable.
If a variable p contains the address of another variable q, then p is said to point to q.

To declare a pointer variable: add a asterisk to the type you want to point to.
int *a;
Declares a variable a of type int *, which can be used to hold the address of (or a “pointer to”) an integer.

Two unary operators (“inverses”):
& operator - “address of” operator.
Returns the address of the variable it precedes.
int *p = &q;
* operator - “dereference” or “value of” operator.
Accesses the variable that the pointer points to.
Returns the value stored at the address that the pointer points to.
int r = *p;
Pointers: Example 1


void main() {
int x = 1, y = 2, z = 3;
int *ip;
ip = &x;
z = *ip;
printf("%d", z); // prints value to x
printf("%d", *ip); // prints value to x
}




The * operator dereferences the pointer to get at the variable we’re pointing to.
In short: don’t confuse the * (dereference/value of) operator with the * in the declaration of a pointer variable (or with multiplication)!
int *p; // pointer declaration
*p = 100; // dereferencing

Another Example

int x = 1, y = 2;
int *ip;
char c;
char *cp;
ip = &x; /* ip now points to x */
printf( "%d\n", *ip ); /* prints 1 */
printf( "%d\n", *ip + 2 );
/* prints 3 */

y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
printf( "%d\n", x ); /* prints 0 */
//cp= &x; /* doesn’t work; types don’t match */
/*cp is not pointing anywhere */
*cp = ’z’;

cp = &c;
*cp = 'z';
printf( "%c\n", c ); /* prints z */

Pointer Arithmetic

Pointer addition: pointer plus int
if a pointer p points to an element of an array, then p + i is a pointer (of the same type) pointing to the ith element after the element pointed to by p.
Pointer subtraction: pointer minus pointer
If p and q point to elements of the same array, then q - p gives the number of elements between p and q.

Pointer comparison: pointer relation pointer
Permissible relations: ==, !=, <, <=, >, >=
If p and q point to elements of the same array, then p < q is true if p points to an earlier member of the array than q does. Note: CAN’T add two pointers, or perform any sort of multiplication, etc. A pointer is a physical memory location, represented by an integer, but you should never think of them as integers. (Try it!). Pointer arithmetic works at the level of “the next element in the array”, NOT at “the next physical memory address”.
Don’t Get Confused!

 Post by j.siam,
 Ref-: Md Munirul Haque