Академический Документы
Профессиональный Документы
Культура Документы
Pointers
4.2: I'm trying to declare a pointer and allocate some space for it,
but it's not working. What's wrong with this code?
char *p;
*p = malloc(10);
p = malloc(10);
It's when you're manipulating the pointed-to memory that you use
* as an indirection operator:
*p = 'H';
References: K&R1 Sec. 5.1 p. 91; K&R2 Sec. 5.1 p. 95; ANSI
Sec. 3.3.2, Sec. 3.3.3; ISO Sec. 6.3.2, Sec. 6.3.3; H&S
Sec. 7.4.4 pp. 192-3, Sec. 7.5 p. 193, Secs. 7.5.7,7.5.8 pp.
199-
200.
4.5: 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 does not mean "pretend these bits have a
different type, and treat them accordingly"; it is a conversion
operator, and by definition it yields an rvalue, which cannot be
assigned to, or incremented with ++. (It is an anomaly in pcc-
derived compilers, and an extension in gcc, that expressions
such as the above are ever accepted.) Say what you mean: use
p += sizeof(int);
void f(ip)
int *ip;
{
static int dummy = 5;
ip = &dummy;
}
int *ip;
f(ip);
A: Are you sure the function initialized what you thought it did?
Remember that arguments in C are passed by value. The called
function altered only the passed copy of the pointer. You'll
either want to pass the address of the pointer (the function
will end up accepting a pointer-to-a-pointer), or have the
function return the pointer.
f(&5);
int five = 5;
f(&five);
References: K&R1 Sec. 1.8 pp. 24-5, Sec. 5.2 pp. 91-3; K&R2
Sec. 1.8 pp. 27-8, Sec. 5.2 pp. 91-3; ANSI Sec. 3.3.2.2, esp.
footnote 39; ISO Sec. 6.3.2.2; H&S Sec. 9.5 pp. 273-4.
4.12: I've seen different methods used for calling functions via
pointers. What's the story?
r = fp();
References: K&R1 Sec. 5.12 p. 116; K&R2 Sec. 5.11 p. 120; ANSI
Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale Sec. 3.3.2.2; H&S
Sec. 5.8 p. 147, Sec. 7.4.3 p. 190.