Comparison of Pascal and C - Pointers

Pointers

In C, pointers can be made to point at most program entities, including objects or functions:

int a; int *b; int (*compare)(int c, int d); int MyCompare(int c, int d); b = &a; compare = &MyCompare;

In C, since arrays and pointers have a close equivalence, the following are the same:

a = b; a = *(b+5); a = *(5+b); a = 5;

Thus, pointers are often used in C as just another method to access arrays.

To create dynamic data, the library functions malloc and free are used to obtain and release dynamic blocks of data. Thus, dynamic memory allocation is not built into the language processor. This is especially valuable when C is being used in operating system kernels or embedded targets as these things are very platform (not just architecture) specific and would require changing the C compiler for each platform (or operating system) that it would be used on.

Pascal doesn't have the same kind of pointers as C, but it does have an indirection operator that covers the most common use of C pointers. Each pointer is bound to a single dynamic data item, and can only be moved by assignment:

type a = ^integer; var b, c: a; new(b); c := b;

Pointers in Pascal are type safe; i.e. a pointer to one data type can only be assigned to a pointer of the same data type. Also pointers can never be assigned to non-pointer variables. Pointer arithmetic (a common source of programming errors in C, especially when combined with endianness issues and platform-independent type sizes) is not permitted in Pascal. All of these restrictions reduce the possibility of pointer-related errors in Pascal compared to C, but do not prevent invalid pointer references in Pascal altogether. For example, a runtime error will occur if a pointer is referenced before it has been initialized or after it has been disposed.

Read more about this topic:  Comparison Of Pascal And C