Artificial arrays

It's often useful to print out several successive objects of the same type in memory; a section of an array, or an array of dynamically determined size for which only a pointer exists in the program.

You can do this by referring to a contiguous span of memory as an artificial array, using the binary operator @. The left operand of @ should be the first element of the desired array and be an individual object. The right operand should be the desired length of the array. The result is an array value whose elements are all of the type of the left operand. The first element is actually the left operand; the second element comes from bytes of memory immediately following those that hold the first element, and so on. For example, if a program says:

int *array = (int *) malloc (len * sizeof (int));

you can print the contents of array with:

p *array@len

The left operand of @ must reside in memory. Array values made with @ in this way behave just like other arrays in terms of subscripting, and are coerced to pointers when used in expressions. Artificial arrays most often appear in expressions via the value history (see ), after printing one out.

Another way to create an artificial array is to use a cast. This reinterprets a value as if it were an array. The value need not be in memory:

(gdb) p/x (short)0x12345678
\$1 = {0x1234, 0x5678}

As a convenience, if you leave the array length out — as in (type[])value — gdb calculates the size to fill the value as sizeof( value )/sizeof( type ). For example:

(gdb) p/x (short[])0x12345678
\$2 = {0x1234, 0x5678}

Sometimes the artificial array mechanism isn't quite enough; in moderately complex data structures, the elements of interest may not actually be adjacent—for example, if you're interested in the values of pointers in an array. One useful workaround in this situation is to use a convenience variable (see ) as a counter in an expression that prints the first interesting value, and then repeat that expression via Enter. For instance, suppose you have an array dtab of pointers to structures, and you're interested in the values of a field fv in each structure. Here's an example of what you might type:

set \$i = 0
p dtab[\$i++]->fv
Enter
Enter
...