60 likes | 135 Views
Learn about using const with pointers in C programming, including nonconstant pointers to nonconstant data, nonconstant pointers to constant data, constant pointers to nonconstant data, and constant pointers to constant data. Discover the nuances of pointer arithmetic and how to avoid logic errors when working with pointers.
E N D
Using const with pointers 4 ways
Nonconstant pointer to nonconstant data The data can be modified through the dereferenced pointer, and the pointer can be modified to point to other data. An example declaration is: int *countPtr
Nonconstant pointer to constant data The pointer can be modified to point to any data item of the appropriate type, but the data to which it points cannot be modified through THAT pointer. An example declaration is: constint *countPtr; read as countPtr is a pointer to an integer constant.
constant pointer to Nonconstant data A pointer that always points to the same memory location; the data at that location CAN be modified through the pointer. An example is an array name, which is a constant pointer to the beginning of the array.
constant pointer to constant data A pointer that always points to the same memory location; the data at that location CANNOT be modified through the pointer. This is how an array should be passed to a function that only reads the array and does not modify it!
Pointer Arithmetic Is pointless unless used on a pointer that points to an array. You cannot assume that two integers, say, are stored next to each other in memory! Subtracting or comparing two pointers that do not refer to elements of the same array is a logic error! A void pointer cannot be dereferenced. An array can be thought of as a constant pointer.