Page 41 - C-Language
P. 41
float eval = 77;
fun(&eval, &fval);
all goes well and something like
is 4 equal to 4?
is printed. If we pass the same pointer, the program will still do the right thing and print
is 4 equal to 22?
This can turn out to be inefficient, if we know by some outside information that e and f will never
point to the same data object. We can reflect that knowledge by adding restrict qualifiers to the
pointer parameters:
void fan(float*restrict e, float*restrict f) {
float a = *f
*e = 22;
float b = *f;
print("is %g equal to %g?\n", a, b);
}
Then the compiler may always suppose that e and f point to different objects.
Changing bytes
Once an object has an effective type, you should not attempt to modify it through a pointer of
another type, unless that other type is a character type, char, signed char or unsigned char.
#include <inttypes.h>
#include <stdio.h>
int main(void) {
uint32_t a = 57;
// conversion from incompatible types needs a cast !
unsigned char* ap = (unsigned char*)&a;
for (size_t i = 0; i < sizeof a; ++i) {
/* set each byte of a to 42 */
ap[i] = 42;
}
printf("a now has value %" PRIu32 "\n", a);
}
This is a valid program that prints
a now has value 707406378
This works because:
• The access is made to the individual bytes seen with type unsigned char so each modification
is well defined.
• The two views to the object, through a and through *ap, alias, but since ap is a pointer to a
https://riptutorial.com/ 17

