Pointers

Cards (17)

  • Pointers are used frequently in C, as they have a number of useful applications.
  • Pointers can be used to pass information back and fort between a function and its reference point. In particular, pointers provide a way to return multiple data items from a function via function arguments.
  • Pointers also permit references to other functions to be specified as arguments to a given function. This has effect of passing functions as arguments the given function.
  • Pointers are also closely associated with arrays and therefore provide an alternate way to access individual array elements.
  • Pointers provide a convenient way to represent multidimensional arrays, allowing a single multidimensional array to be replaced by a lower-dimensional array of pointers. This feature permits a collection of strings to be represented within a single array, even though the individual strings may differ in length.
  • Address operator - is the one who evaluates the address of its operand
  • Indirection operator - also known as dereference
  • Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator and a pointer.
  • Ampersand (&) operator - denotes an address in memory
  • Pointer - is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable.
  • A pointer is a variable that represents a location rather than the value of a data item, such as a variable of an array element.
  • When a pointer variable is declared, the variable name must be preceded by an asterisk(*).
  • The allocation of memory in this manner, as it is required, is known as dynamic memory allocation.
  • To assign sufficient memory for x, we can make use of library function malloc, as follows: x = malloc(x *sizeof(int));
  • This function reserves a block of memory whose size(in bytes) is equivalent to the size of integer quantity. The function returns a pointer to the character. To be consistent with the definition of x, we really want a pointer to an integer. However, characters and integers are equivalent in C. Therefore, the statement is acceptable as shown above, though we could include a type cast to be on the safe side, that is,
    x = (int ) malloc(10sizeof(int));
  • As a result, the use of a pointer variable to represent an array requires some sort of initial memory assignment before the array elements are processed.
  • Pointer arithmetic is one of the most powerful features of C.