Source Code for C Pointers

 

This blog is explained at this 

Here is the source code for CPointersBasic project of “https://www.youtube.com/watch?v=fjMA3zMwdeM” :

/*
============================================================================
Name : cPointerBasics.c
Author : sk
Version :
Copyright : Embedkari
Description : Hello World in C, Ansi-style
============================================================================
*/

#include <stdio.h>
#include <stdlib.h>
void demo_ptr_scope();
void demo_void_ptr(void *);
void demo_ptr_types();

/****LEARNING Objective
* WILD Pointer
* NULL Pointer
* DANGLING Pointer
* VOID Pointer
* ENDIANNESS
*/
int main(void) {
demo_ptr_types();
return EXIT_SUCCESS;
}

void demo_ptr_scope()
{
unsigned int* testPtr=NULL;

if(!testPtr) {
unsigned int x=0x1234;
testPtr = &x;
printf(” testPtr addr=%lx data=%x \r\n”,testPtr,*testPtr) ;
}
unsigned int y=0x5678;
printf(” y addr=%lx data=%x \r\n”,&y,y) ;
/****WAIT Why following statement is commented ? ***/
//printf(“val of x=%x \r\n”,x);
printf(“Trying to read Dangling testPtr addr=%lx data=%x \r\n”,testPtr,*testPtr) ;
}

/*** This function demonstrate Void Pointer and Little/Big Endian concept **/
void demo_void_ptr(void *tmp)
{
unsigned char x=0xAB;
unsigned short y=0xABCD;
unsigned char *myPtr;
unsigned short* myPtr1;
myPtr=tmp;
printf(“myPtr addr=%lx \r\n”,myPtr) ;
/**WAIT*****READ myPtr value in console, look at Memory window What value you expect after execution ofnext LINE*******/
printf(“myPtr data=%x\r\n”,*myPtr) ;
myPtr=&x;
/**WAIT***** What value you expect after execution ofnext LINE*******/
printf(“myPtr addr=%lx data=%x\r\n”,myPtr,*myPtr) ;
myPtr1=&y;
printf(“myPtr1 addr=%lx \r\n”,myPtr1) ;
/**WAIT*****READ myPtr value in console, look at Memory window What value you expect after execution ofnext LINE*******/
printf(“myPtr1 data=%x\r\n”,*myPtr1) ;
demo_ptr_scope();
}

void demo_ptr_types()
{
unsigned int *myPtr, *myPtr1; //This un-initialize pointer is known as Wild pointer;
myPtr=NULL ;// Now it is not Wild and called NULL pointer. It has a definite value but still not
// pointing to any valid address/object
myPtr=malloc(sizeof(unsigned int));
if (myPtr) {
printf(“Valid myPtr address=%lx \r\n”,myPtr) ;
*myPtr=0x12345678 ;
} else{
printf(“Memory Allocation Failed \r\n”);
}
/**WAIT***** What value you expect after execution ofnext LINE*******/
printf(“data at myPtrs=%x \r\n”,*myPtr) ;
demo_void_ptr(myPtr);
free(myPtr);
myPtr1=malloc(sizeof(unsigned int));
if (myPtr1) {
*myPtr1=0xaabbccdd;
printf(“Valid myPtr1 address=%lx data=%x \r\n”,myPtr1,*myPtr1) ;

} else{
printf(“Memory Allocation Failed \r\n”);
}
printf(“Trying to read Dangling Pointer=%lx data=%x \r\n”,myPtr,*myPtr) ; //Dangling pointer
}

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.