C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
printf("The first array value is %d.\n", vals[0]);
printf("The second array value is %d.\n", vals[1]);
printf("The third array value is %d.\n", vals[2]);
printf("The fourth array value is %d.\n", vals[3]);
printf("The fifth array value is %d.\n", vals[4]);

does exactly the same as this set:


Click here to view code image


printf("The first array value is %d.\n", *(vals + 0));
printf("The second array value is %d.\n", *(vals +1));
printf("The third array value is %d.\n", *(vals + 2));
printf("The fourth array value is %d.\n", *(vals + 3));
printf("The fifth array value is %d.\n", *(vals + 4));

If vals is a pointer constant (and it is), and the pointer constant holds a number that is the address to
the array’s first element, adding 1 or 2 (or whatever) to vals before dereferencing vals adds 1 or
2 to the address vals points to.


Tip

If you’re wondering about the importance of all this mess, hang tight. In a moment,
you’ll see how C’s pointer notation lets you make C act almost as if it has string
variables.

As you might remember, integers usually take more than 1 byte of memory storage. The preceding
printf() statements appear to add 1 to the address inside vals to get to the next dereferenced
memory location, but C helps you out here. C adds one int size when you add 1 to an int pointer
(and one double size when you add 1 to a double pointer, and so on). The expression *(vals +
2) tells C that you want the third integer in the list that vals points to.


Characters and Pointers


The following two statements set up almost the same thing in memory. The only difference is that, in
the second statement, pName is a pointer variable, not a pointer constant:


Click here to view code image


char name[] = "Andrew B. Mayfair"; /* name points to A */
char * pName = "Andrew B. Mayfair"; /* pName points to A */

Because pName is a pointer variable, you can put it on the left side of an equals sign! Therefore, you
don’t always have to use strcpy() if you want to assign a character pointer a new string value.
The character pointer will only point to the first character in the string. However, %s and all the
string functions work with character pointers just as easily as with character arrays (the two are the
same thing) because these functions know to stop at the null zero.


To put a different name in the name array, you have to use strcpy() or assign the string one
character at a time—but to make pName point to a different name, you get to do this:

Free download pdf