aryeh@eddie.mit.edu (Aryeh M. Weiss) (04/07/90)
In article <6074@ozdaltx.UUCP> root@ozdaltx.UUCP (root) writes: > >My reference is The K & R C PROGRAMMING LANGUAGE, pg 99-105. >Unless I totally missed it, nowhere does it mention that a pointer >Has to be initialized or space allocated. In a couple of places >it sorta hints at it now that I know what the problem is. > >Pointers have always been a point of confusion for me... > It is a point of confusion for lots of people, due in part to the syntactic similarity between pointer usage and array usage in C. The semantic difference is rather large. You should consider pointers to be variables as you would int's or double's. You would not use an int or double which has not been initialized, would you? This would be a semantic error, though not a syntactic error. Array's on the other hand are fixed locations in memory (or on the stack if they are local to a procedure). You might think of them as address constants, just as (-2) or (3.14) are constants. So you can assign an array to a pointer, just as you can assign (3.14) to a double, but obviosly not vice versa. Strings (constants) are handled special, as they are stored by the compiler as a static array of characters. Thus you can say, char *x; x = "Hello"; >If I understand correctly, a character array actually takes LESS >memory than a corresponding pointer array. And would be preferable in >most instances where passing the address isn't needed. This is true, because the pointer (as well as storage used by the malloc routines) represents extra overhead. The problem with arrays is that they are fixed in size. Depending on the application, you win if you are using pointer arrays to keep track of a large number of strings that are widely varying in size. This is done by using the memory allocation routines, strdup, malloc, and realloc. You can also use malloc/realloc to allocate storage for the pointer array if you want the number of objects (strings, structures, unions, etc) you are pointing to be open ended. Dynamic memory allocation is a very powerful tool and allows an application great flexibility. I hope this gives some more insight on pointer usage. --