Address Of Variable


Already we have learned the basic concept of pointer, memory organization. Now we have to learn accessing the address of a variable before learning the declaration and initialization of pointer variable. 

In compiler we can do it by adding ampersand ('&' sign) before normal variable. If we want to access the address of memory of 'variable_name' then we have to do write '&variable_name' on compiler what we used in scanf () function before.

Example:

int a;
scanf(“%d”,&a);

To access the address of a variable name:
&variable
Now run the following code on your compiler. It will show you the address of variable_name.

#include <stdio.h>
int main()
{
     /*Variable Declaration*/
    int variable_name, variable_address;
     /*Assigning the address of variable_name to variable_address*/
    variable_address = &variable_name;
    printf("Address of variable_name: %u\n",variable_address);
    return 0;
}
By following the method we can't access the address of constant, array name, any expression. So the following methods are illegal.

int variable_address = &100;
int arr[6], variable_address = &arr;
int a, b, variable_address; variable_address = &(a-b);
You may be confused if you need to access the address of an array or any element of array how you will do it. You can do it by following the methods.
array_address = &array_name[0];
To access the address of array: You have to add ampersand before array name with 0 size. Because, the address of 0th element is the address of array. So if we want to assign the address of array_name[10] to array_address then we have to do:
array_address = &array_name[0];

Now run the following code.



#include <stdio.h>
int main()
{
     /*Variable Declaration*/
    int array_name[10], array_address;

     /*Assigning the address of array_name to array_address*/
    array_address = &array_name[0];
    printf("Address of array_name: %u\n",array_address);

    return 0;

}
Similarly you can access the address of any element of array. To see it you can run the following program.


#include <stdio.h>
int main()
{
    /*Array Declaration and Initialization*/
    int array_name[3] ={23, 43, 56};
    /*Address of First Element*/
    printf("Address of array_name: %u\n",&array_name[0]);
     /*Address of Second Element*/
    printf("Address of array_name: %u\n",&array_name[1]);
    /*Address of Third Element*/
    printf("Address of array_name: %u\n",&array_name[2]);

    return 0;

}
Question for test

1. How do you access the address of a integer variable and assign the address of variable to another integer variable?
2. How can access the address of a string?
3. Is it possible to access the address of value of a variable?
4. Find out the address of 4th element of the following array.
Int salary[5] = {4000, 4500, 5000, 3000, 6000}