1.I had the definition char x[6] in one source file, and in another I
declared extern char *x. Why didn’t it work?
A:The declaration extern char *x simply does not match the actual
definition. Use extern char x[].
2. But I heard that char x[] was identical to char *x.
A:Not at all. Arrays are not pointers.
3.You mean that a reference like x[3] generates different code
depending on whether x is an array or a pointer?
A:Precisely.
4.So what is meant by the “equivalence of pointers and arrays” in C?
A:An lvalue of type array-of-T which appears in an expression decays
into a pointer to its first element; the type of the resultant
pointer is pointer-to-T.
5.Why are array and pointer declarations interchangeable as function
formal parameters?
A:Since functions can never receive arrays as parameters, any
parameter declarations which “look like” arrays are treated by the
compiler as if they were pointers.
6.Someone explained to me that arrays were really just constant
pointers.
A:An array name is “constant” in that it cannot be assigned to, but
an array is _not_ a pointer.
7.I came across some “joke” code containing the “expression”
5["abcdef"] . How can this be legal C?
A:Yes, array subscripting is commutative in C. The array
subscripting operation a[e] is defined as being equivalent to
*((a)+(e)).
8.My compiler complained when I passed a two-dimensional array to a
routine expecting a pointer to a pointer.
A:The rule by which arrays decay into pointers is not applied
recursively. An array of arrays (i.e. a two-dimensional array in
C) decays into a pointer to an array, not a pointer to a pointer.
9.How do I declare a pointer to an array?
A:Usually, you don’t want to. Consider using a pointer to one of the
array’s elements instead.
10.How can I dynamically allocate a multidimensional array?
A:It is usually best to allocate an array of pointers, and then
initialize each pointer to a dynamically-allocated “row.” See the
full list for code samples.
11.I have a char * pointer that happens to point to some ints, and I
want to step it over them. Why doesn’t “((int *)p)++;” work?
A: In C, a cast operator is a conversion operator, and by definition
it yields an rvalue, which cannot be assigned to, or incremented
with ++.
No comments:
Post a Comment