Showing posts with label C. Show all posts
Showing posts with label C. Show all posts


Difference between const char *p and char *const p


const char *p and char *const p  both look similar, but are different!
const char *p -- It is a non constant pointer to constant data. That means the data to which it is pointing can never be changed.
For example,
char mychar = 'a';
const char *p = & mychar;
*p = 'b'; //not possible as value at pointer is constant i.e. 'a'

char *const p  -- It is a constant pointer to non constant data. That means, this pointer points to address that is constant and thus pointer cannot point to other address.
For example,
char mychar = 'a';
char mychar2 = 'z';
const char *p = &mychar;
*p = 'b';
p = &mychar2; //not possible as you cannot change address value of pointer


Difference between malloc and calloc in C

Malloc and Calloc are functions provided to allocate memory at run time.Both of these functions return pointer to first block of  allocated memory in success and return null in case of failure.
Though their purpose is same, there are few differences between them.


1. No. of Arguments: 
Both these functions vary in number of arguments they accept.


void *malloc(size_t size);

void *calloc(size_t n, size_t size);

Malloc takes only one argument that describes size of block to be allocated in memory.

e.g. oPointer = (int *)malloc(sizeof(int) * 2); will allocate size of 4 bytes(size of int is 2 bytes).
Whereas, Calloc takes two arguments number of blocks and size of each block.
e.g. oPointer = (int *)calloc(2 ,sizeof(int)); will allocate size of 4 bytes(size of int is 2 bytes).


2. Default Initialization: 
Malloc does not initialize the memory allocated whereas calloc initializes the allocated memory to default (e.g. Zero).


3. Calculation of memory reuired:
Malloc function does not calculate total memory to be allocated, the argument itself describes the total memory whereas, calloc accepts two argument and internally calculates their product to find total memory to be allocated.