Programming C: Posts 11 – Pointers in c

1. Introduction pointers in C

The variables we have known and used in the past are variable in size and data type identified. They call this type variables are static variables. When you declare a static variable, a memory cell for the variable amount will be allocated without knowing during program execution using all of its memory cells or not. On the other hand, This form of static variables will exist during program execution, despite the changes that the program uses only 1 disposable.

Some restrictions may encounter when using static variables:

  • Allocate memory cell balance, cause wasted memory cells.
  • Allocate memory cells lacking, program execution error.

To avoid the limitations on, C language provides us with a special variable called volatility with the following characteristics:

  • Only arise during program execution, not arising at the start program.
  • When running the program, the size of the variable, memory and memory address is allocated to the variable may change.
  • After you finish using it can liberation to save space in memory. However, the variation does not address certain I will not be able to access them. Therefore, C language provides us with a special kind of variable again to overcome this, pointer variable that is (pointer) with the characteristics:
  • Pointer variable does not contain data that contain the address of the data or contains the address of the memory containing data.
  • The size of the pointer does not depend on the type of data.

2. Pointer

Each variable is declared to have been allocated to 1 certain memory areas where (address) different. Pointer variable used to store the address of the variable.

2.1 Example

// e.g about pointer - code by nguyenvanquan7826
#include <stdio.h>

int main() 
{
    /* khai bao bien x va bien con tro px */
    int x, *px; 
    px = &x;
    /* &x : tra ve dia chi cua bien x
     * px = &x : gan dia chi cua bien x cho px hay px tro den x
     */

    x = 42;

    printf("Vi tri cua bien x la %p \n", &x);
    printf("Noi dung cua bien x la %d \n", x);
    printf("Vi tri cua bien x la %p \n", px);
    printf("Noi dung cua bien x la %d \n", *px);

    *px = 7826;
    printf("\n -------- \n\n");

    printf("Noi dung cua bien x la %d \n", x);
    printf("Noi dung cua bien x la %d \n", *px);

    return 0;
}

Result:

Result:
The record x la 42
Vi tri cua well x 0x7ffe064348fc
The record x la 42

--------
The record x la 7826
The record x la 7826

Through this opening example we can draw the following points:

the. Declare cursor variables

For each type of data we have respectively a pointer variable of that type.

Type * Name pointer;

In the above example we declare 1 pointer variable of type int px.

b. Regulation of pointers that point to the

We use the operator & for address 1 variable and then assign that address pointer.
Name pointer = &variable;

c. How to access

With the cursor px above have 2 Though the permit is:

  • px : Get the address to which it kept (point to)
  • *px : Get the value of the memory that it points to.

In the example above we can see that after the assignment px = &x; then we write the:

  • px would be equivalent to &x
  • *px is equivalent to x. and can be used in the calculations * px, expression.

d. Some operations on pointer

// e.g about pointer - code by nguyenvanquan7826
#include <stdio.h>

int main() 
{
    /* khai bao bien x va 2 bien con tro px, qx */
    int x, *px, *qx; 
    px = &x;

    printf("Nhap gia tri cho vung nho px tro toi: ");
    scanf("%d", px); 
    /* px la con tro nen khong viet scanf("%d", &px);  */

    qx = px; /* gan gia tri cua px cho qx, qx cun tro toi x*/

    printf("Vi tri cua bien x la %p \n", &x);
    printf("Vi tri cua bien x la %p \n", px);
    printf("Vi tri cua bien x la %p \n", qx);
    printf("Noi dung cua bien x la %d \n", x);
    printf("Noi dung cua bien x la %d \n", *px);
    printf("Noi dung cua bien x la %d \n", *qx);

    // tang gia tri cua o nho len, <=> x = x + 7826
    *px += 7826; 
    printf("Noi dung cua bien x la %d \n", x);

    px++; 
    /* cong them mot don vi cho px
     *  => px tro toi vung nho tiep theo
     */

    printf("Vi tri px tro toi la %p \n", px);

    return 0;
}

Result:

Enter a value for the cove px ash toi: 42
Vi tri well cua x 0xbfba58a0
Vi tri well cua x 0xbfba58a0
Vi tri well cua x 0xbfba58a0
The record x la 42
The record x la 42
The record x la 42
The record x la 7868
Vi tro sort px thee 0xbfba58a4

For eg we saw on some operations on pointers common after: (in addition to many other operations).

  • 2 pointer variable of the same type can be assigned to each other or perform public accounting for an integer, minus 2 pointers for each. In the example above we perform calculations:
  • Assign: q x = px; When it receives the value of px qx is the address of the variable x, ie px and qx and pointing to x. In addition we can assign the following: q x = px + 2; with qx, px is the same pointer type. Subtraction 2 pointer of the same type will return 1 integer values (int). This is the distance (Some elements) between 2 including pointers
  • Increase: The permit to increase or decrease, subtraction is performed on the same pointer arithmetic variables. The only difference is that it rises and falls, plus or minus according to the type of single byte that it has.
    CEO. In the above example it is possible to increase: px ; When assuming this is pointing to the address px: 0xbfba58a0, then allowed to increase its value is (point to the location) 0xbfba58a4 (increase 4) because px is that each pointer variable of type int int accounts 4 byte in memory.
  • In addition we are allowed to change the value of the variable x by * px math = 3; In essence this operation was to change the value in the memory (address) that px points to, which led to the value of the variable x is changed according to.

Have you noticed:

  • Depending on the compiler or the operating system that is the capacity of different types. (This is the translation of type int accounts 4 byte, but in the other services it occupies 2 byte). For each type of storage you use sizeof() but in all 2 mentioned.
  • Also, depending on the operating system each pointer variable, no matter what type of cursor (int, float, double,...) also accounts for the same number of bytes. Operating system 32 bit the pointer variable accounting 4 byte, operating system 64 bit the pointer variable accounting 8 byte.

3. Allocate and recover memory

the. Allocation:

Prior to this one small example.

// e.g about pointer - code by nguyenvanquan7826
#include <stdio.h>

int main() 
{
    int *px;
    *px = 42;
    printf("Vi tri con tro px la %p \n", px);
    printf("Gia tri con tro px tro toi la %d \n", *px);
    return 0;
}

When compiled, it will not benefit (warning), when run will not be able to run that program will back out.
The reason is that when the cursor variable declaration px the new machine only provide 2 byte to store the address of the pointer variable that has not allocate memory for the pointer data storage px. (similar cooperative supply 2 Kg of rice for you to do the same but does not give you the land to you that plated ring ).

Noted: There are a number of compiler error but still will not run normally, but the best is that we should allocate Use. This error appears most clearly when you use the pointer to the array which we will discuss in later.

Well we went on key issues, how to allocate memory for pointers.
To allocate memory for pointers we use the following function in the library stdlib.h.

  • malloc : cursor name = (pointer type *) malloc (sizeof(pointer type));
  • calloc : cursor name = (pointer type *) malloc (n, sizeof(pointer type));

In that sizeof(pointer type) the size of the type; n is the number of sizeof(pointer type) granted.

// e.g about pointer - code by nguyenvanquan7826
#include <stdio.h>
#include <stdlib.h>

int main() 
{
    int *px, *qx;
    px = (int *) malloc(sizeof(int));
    qx = (int *) calloc(1, sizeof(int));

    printf("Vi tri con tro px la %p \n", px);
    printf("Gia tri con tro px tro toi la %d \n", *px);

    printf("Vi tri con tro qx la %p \n", qx);
    printf("Gia tri con tro qx tro toi la %d \n", *qx);
    return 0;
}

Here you note: The only difference between malloc and calloc that you simply understand when allocated with malloc allocates the machine px 1 cell any cell without knowing what data is or no data (* px so valuable as above) calloc, too, but also other 1 Points are allocated after the machine will automatically assign values ​​always 0 the memory cell that refers to the variable qx, News qx default value is 0.
When allocating the pointer 1 certain amount of memory cells during the process of work we lack and need to allocate more, we use the command realloc:

cursor name = (pointer type *) realloc (cursor name, the amount allocated to * sizeof(pointer type));

In that: = amount allocated to old + new.
CEO: Initially we allocated the pointer is px 10 memory cells.
Then it wants to allocate more 5 more memory cells, the amount allocated = 15.

b. Recovery and check the remaining memory

To recover the memory allocation functions we use free(cursor name);

3. The function of the cursor

As in all Permutation function in C we know how to pass parameters a,b in HoanVi function is passing by value, not by transmission by address (or parameters) so even though the value of the function variables were changed, but after the function is done, the value has yet to be changed. And we will be revised by passing parameters form a cursor and pointer b to the swap can be swapped at the address of the memory cells that. And when we get the desired result.

// e.g about pointer - code by nguyenvanquan7826
#include <stdio.h>

void hoanVi(int *a, int *b) 
{
     int temp = *a;
     *a = *b;
     *b = temp;
}

int main() 
{
    int a = 42, b = 7826;
    printf("Truoc khi goi ham hoan vi: a = %d, b = %d \n", a, b);

    hoanVi(&a, &b);

    printf("Sau khi goi ham hoan vi: a = %d, b = %d \n", a, b);

    return 0;
}