position: fixed; top: auto !important; margin-left: 112px;

Pointers in C

What happens in memory when we write the statement like this?

int i = 3 ;

The compiler will tell the memory to store value 3 at some location and name that location as 'i' .It looks like this,


Diagram itself is explanatory. The value of 'i' is 3 and it is stored at some location Number. You don't have to worry about the location Number. Memory will automatically handle this.

void main()
{
  int a = 5;
  printf("Address of variable a = %u", &a);

  printf("Value of variable a = %d", a);
/* Get the value of 'a' using pointers */
  printf("Value of variable a = %d", *(&a));

Output

Address of variable a = 12345678
Value of variable a = 5
Value of variable a = 5

* asterik indicates that the variable is pointer variable. The third printf statement

 printf("Value of variable a = %d", *(&a));

Here , first we get the address of variable 'a' using &a and apply that address * to get the value at that specific address.

What are Pointers?

Pointers in C are used to get the value at a specific address. Pointers in C are denoted by *(Asterisk symbol).

Syntax

Datatype *variableName;

Example

int *a;
float *b;
float **b;
float ***b;

C Pointers Example

int i=3;                                              
j = &i;  

Always read * as "Value at"

 Assume 1000 & 1004 are the addresses of i & j
   i 
 1000 --> 3  
                                                                     
   j
1004 --> 1000    
                            
            
*j -->  Read Value at j 
        Value at 1000
        What is the value at 1000 Address? :) 

*j --> 3                    
   

/* Yes, you have to read the c pointers like this. */

Example:

int main()
{
    int i=3, *j, k;
    j = &i;
    printf("%d\n", i * *j * i + *j);
    return 0;
}

Output :-

30

Compute the value of j like i explained in above example.

i = 3

*j = 3

i * *j * i + *j 
3 * 3 * 3 + 3  = 30

Always remember , Practice makes you perfect in Pointers :)

Solve the Quiz of Article

1) What do you think output of following will be 30?
int main()
{
    int i=3, *j, k;
    j = &i;
    printf("%d\n", i * *j * i + *j);
    return 0;
}
Yes
No

2) Is output of following program will be 5?
void main()
{
  int a = 5;
  printf("Address of variable a = %u", &a);
}
Yes
No


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.