Originally posted by nsbuttar
the no of unit data types to skip to go to the next unit data type will depend upon what type of value is *t
Very true.
Originally posted by nsbuttar
[...] holding if we typecast the reurned data type by malloc to unsigned * it will skip 4 of if we typecast it to char * it will skip none;
The cast of the return value of malloc is not at all relevant to incrementing a pointer. It is the pointer type that tells the compiler how many bytes to increment the pointer, not the manner in which the pointer was assigned its current value.
Code:
#include<stdio.h>
#include<stdlib.h>
#define WYSIWYG(x) #x, (x)
int main(void)
{
char *t = (int*)malloc(15), *copy = t;
if(t)
{
printf("%s = %p\n", WYSIWYG(t));
++t;
printf("%s = %p\n", WYSIWYG(t));
free(copy);
}
return(0);
}
/* my output
t = 007A305C
t = 007A305D
*/
The pointer advanced neither none nor 4. It advanced the expected 1. Let's try that the other way around. I'd expect my pointer to advance sizeof(int), which is 4 for the following.
Code:
#include<stdio.h>
#include<stdlib.h>
#define WYSIWYG(x) #x, (x)
int main(void)
{
int *t = (char*)malloc(15), *copy = t;
if(t)
{
printf("%s = %p\n", WYSIWYG(t));
++t;
printf("%s = %p\n", WYSIWYG(t));
free(copy);
}
return(0);
}
/* my output
t = 007A305C
t = 007A3060
*/
Yup. I see casting the return value of malloc as all cost and no benefit.