Difference between revisions of "Interview Preparation Pointers"
From Embedded Systems Learning Academy
Proj user14 (talk | contribs) |
Proj user14 (talk | contribs) |
||
| Line 49: | Line 49: | ||
'''Passing Pointers to a Function''' | '''Passing Pointers to a Function''' | ||
| − | + | In the code below we have a defines a function values , which return void . It takes two parameters which are pointers to an integer. When the function is called the address of the integer is passed and not the value . | |
<pre> | <pre> | ||
| Line 77: | Line 77: | ||
} | } | ||
| − | |||
</pre> | </pre> | ||
Revision as of 17:09, 18 December 2016
Pointers : A pointer is a variable who's value is address of some other variable i.e. it can be address of some memory location.
<varaible_type> *<name>
eg :
int *pointer_to_integer
The above example , we have declared a pointer to a variable (pointer_to_integer), the variable stores the address of an integer .
Implementation of Pointer :
Code:
#include <stdio.h>
int main(void) {
int var = 20;
int *p;
p = &var;
printf("Pointer %d\n",var);
printf("Pointer %d\n",&var); // Prints the address of the varaible (var)
printf("Pointer %d\n",p);
printf("Pointer %d\n",*p); // Prints the value that (p) points to
return 0;
}
Output :
Pointer 20
Pointer 1809844068
Pointer 1809844068
Pointer 20
Malloc
The Malloc function dynamically allocates memory when required. The function allocates size of byte of memory and returns a pointer to the first byte of NULL.
Syntax: pointer = (type)malloc(size in bytes); Code: int* p; //Declare pointer p = (int*)malloc(sizeof(int)); // Pointer equal to pointer type int that contain memory address space of int *p = 5; // Finally pointer points to location containing value 5
Passing Pointers to a Function
In the code below we have a defines a function values , which return void . It takes two parameters which are pointers to an integer. When the function is called the address of the integer is passed and not the value .
Code:
#include <stdio.h>
/* function declaration */
void value(int *num_ptr_1, int *num_ptr_2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
/* calling a function value */
value(&a, &b);
return 0;
}
/* function prints the value of two numbers */
void value(int *num1, int *num2) {
printf("The value of num1 is %d & num2 is %d", *num1 , *num2 );
}