Pointer Why and When we use – coderinme

Now you have a theory about the pointer, it’s notation, address, referencing and dereferencing.
you understand that if we know the address we can find the value so in spite of value just play with an address that what pointers do.
a pointer points to a memory address

Pointer Why and When we use

Let’s take an example
Remember that question in which we have to write a program to interchange the value of two variables. Note:- (both ways using temporary variable and not using any other value)
But we can do it using pointer

void intSwap (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;

You need to know the following –

int a = 5; // an integer, contains value
int *p; // an integer pointer, contains address
p = &a; // &a means address of a
a = *p; // *p means value stored in that address, here 5

Instead of number if there is string then

void charSwap(char* a, char* b){
    char temp = *a;
    *a = *b;
    *b = temp;

So, when you swap like this. Only the value will be swapped. So, for a char* only their first char will swap.

Now, if you understand char* (string) clearly, then you should know that you only need to exchange the pointer. It’ll be easier to understand if you think it as an array instead of a string.

void stringSwap(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;

Pointers are used (in the C language) in three different ways:

To create dynamic data structures. Array, Linked List

To pass and handle variable parameters passed to functions.
To access information stored in arrays. (Especially if you work with links).
Pointer Why and When we usePointer Why and When we use
All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

2 comments: On Pointer Why and When we use – coderinme

Leave a reply:

Your email address will not be published.