Pointer Decay

What is pointer decay????

ยท

1 min read

Issue โš 

As array variables are slightly different from pointer variables, we need to be careful when we assign arrays to pointers. If we assign an array to a pointer variable, then the pointer will only contain address of array and the size is lost due to which array variable is decayed to a pointer. ๐Ÿค”๐Ÿคจ

Although we can use printf() function to print whole string without any issues but when it comes to other data types like int arrays we are not able to traverse it because of not knowing size of array and can cause compile errors or unallocated memory access errors in C. ๐Ÿ˜ฎ๐Ÿ˜ฎ

These things can cause subtle bugs in our program, so we need to keep track where array decays in your code. ๐Ÿž๐Ÿž

This bug is applicable to both methods char *arr as well as char arr[]

Solution โœ…

Always pass size of array when passing an array to a function in C. In this way we explicitly passed lost information, successfully handling the decay. ๐Ÿ˜โœ”

ย