Expert C Programming

(Jeff_L) #1

Other Differences Between Arrays and Pointers


Another way of looking at the differences between arrays and pointers is to compare some of their
characteristics, as in Table 4-1.


Table 4-1. Differences Between Arrays and Pointers
Pointer Array
Holds the address of data Holds data
Data is accessed indirectly, so you first retrieve the
contents of the pointer, load that as an address (call it "L"),
then retrieve its contents.

If the pointer has a subscript [i] you instead retrieve the


contents of the location 'i' units past "L"

Data is accessed directly, so for a[i] you
simply retrieve the contents of the
location i units past a.

Commonly used for dynamic data structures Commonly used for holding a fixed
number of elements of the same type of
data

Commonly used with malloc(), free() Implicitly allocated and deallocated


Typically points to anonymous data Is a named variable in its own right

Both arrays and pointers can be initialized with a literal string in their definition. Although these cases
look the same, different things are happening.


A pointer definition does not allocate space for what's pointed at, only for the pointer, except when
assigned a literal string. For example, the definition below also creates the string literal:


char *p = "breadfruit";


Note that this only works for a string literal. You can't expect to allocate space for, for example, a float
literal:


float pip = 3.141; / Bzzt! won't compile */


A string literal created by a pointer initialization is defined as read-only in ANSI C; the program will
exhibit undefined behavior if it tries to change the literal by writing through p. Some implementations
put string literals in the text segment, where they will be protected with read-only permission.


An array can also be initialized with a string literal:


char a[] = "gooseberry";


In contrast to a pointer, an array initialized by a literal string is writable. The individual characters can
later be changed. The following statement:

Free download pdf