Tuesday, March 26, 2019

c - Malloc works without type cast before malloc





I am learning about malloc function & I read this:



ptr= malloc(sizeof(int)*N)


where N is the number of ints you want to create. The only problem is what does ptr point at? The compiler needs to know what the pointer points at so that it can do pointer arithmetic correctly. In other words, the compiler can only interpret ptr++ or ptr=ptr+1 as an instruction to move on to the next int if it knows that the ptr is a pointer to an int. This works as long as you define the ptr to be a pointer to the type of variable that you want to work with. Unfortunately this raises the question of how malloc knows what the type of the pointer variable is - unfortunately it doesn't.



To solve this problem you can use a TYPE cast. This C play on words is a mechanism to force a value to a specific type. All you have to do is write the TYPE specifier in brackets before the value. So:



ptr = (*int) malloc(sizeof(int)*N)



But I have seen many places that they don't use (*int) before the malloc & even I made a linked list with this and had no errors. Why is that?
Also, why do pointers need to know anything except the size of memory they are pointing to?
But then again I am quite new to this, so only the malloc doubt would do for now.


Answer



Before you can use ptr, you have to declare it, and how you declare it is the pointer becomes.

malloc returns void * that is implicitly converted to any type.



So, if you have to declare it like




int *ptr;
ptr = malloc(sizeof(int)*N);


ptr will point to an integer array, and if you declare like



char *ptr;
ptr = malloc(sizeof(char)*N);



ptr will point to a char array, there is no need to cast.



It is advised not to cast a return value from malloc.




But I have seen many places that they don't use (*int) before the
malloc & even I made a linked list with this and had no errors. Why is
that?





Because they (and you also surely) declared the variable previously as a pointer which stores the return value from malloc.




why do pointers need to know anything except the size of memory they
are pointing to?




Because pointers are also used in pointer arithmetic, and that depends on the type it is pointed to.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...