const Pointer in CConstant PointersA constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable. Syntax of Constant PointerDeclaration of a constant pointer is given below: Let's understand the constant pointer through an example. In the above code:
Output In the above output, we can observe that the above code produces the error "assignment of read-only variable 'ptr'". It means that the value of the variable 'ptr' which 'ptr' is holding cannot be changed. In the above code, we are changing the value of 'ptr' from &a to &b, which is not possible with constant pointers. Therefore, we can say that the constant pointer, which points to some variable, cannot point to another variable. Pointer to ConstantA pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed. Syntax of Pointer to ConstantDeclaration of a pointer to constant is given below: Let's understand through an example.
In the above code:
Output The above code runs successfully, and it shows the value of 'ptr' in the output.
In the above code:
Output The above code shows the error "assignment of read-only location '*ptr'". This error means that we cannot change the value of the variable to which the pointer is pointing. Constant Pointer to a ConstantA constant pointer to a constant is a pointer, which is a combination of the above two pointers. It can neither change the address of the variable to which it is pointing nor it can change the value placed at this address. SyntaxDeclaration for a constant pointer to a constant is given below: Let's understand through an example. In the above code:
Output The above code shows the error "assignment of read-only location '*ptr'" and "assignment of read-only variable 'ptr'". Therefore, we conclude that the constant pointer to a constant can change neither address nor value, which is pointing by this pointer. Next Topicvoid pointer in C |