Download presentation
1
Introduction to C Programming CE00312-1
Lecture 16 Pointers in C
2
Pointers Pointers are necessary for understanding and use of:
Passing Parameters by Reference Arrays (especially strings) Dynamic Allocation of Memory Dynamic Data Structures A Pointer is a reference to (or address of) a memory location.
3
1) Passing Parameters by Reference
Function swap exchanges the values of its 2 parameters: #include “stdio.h” void swap(int *, int *); // prototype int main(void) { int a=3, b=7; swap(&a, &b); // addresses of values to be swapped printf(“1st is %d, 2nd is %d”, a, b); return 0; }
4
Function swap void swap(int *x, int *y)
// x, y are copies of the addresses a, b { int temp; temp = *x; // using pointers to access *x = *y; // originals (not copies) *y = temp; // and swap them via temp }
5
2) Arrays and Strings Consider the declaration:
char x[10]; // a string of size 10 x[3] is the character in element 3 of array x &x[3] is the address of element 3 of array x x is the address of array x (actually the same as &x[0]) *x is the character that x points to (ie same as x[0])
6
Strings as pointers Strings should always be declared as arrays inside the main function, so that required storage can be allocated. Thus char x[10] allocates 10 bytes. Strings can be declared explicitly as pointers – typically inside functions, e.g. char *s; declares variable, s, as a pointer to a character – (ie string pointer). It can point to any string –or any part of a string – or to examine all the characters within a string.
7
Arrays as parameters Arrays and strings, such as x above, passed to functions as parameters are already addresses. Example: int list [100]; sort(list, n); The address of array, list, is passed to the sort function. void sort(int a[], int n) So that array, a, also refers to the original elements of list.
8
Example of a String Function
The function, print_reverse, given a string (as a parameter) prints the string in reverse by dealing with one character at a time, using a pointer starting with the last and continuing while it has not yet reached the start of the string.
9
Main function Main function reads, reverse and writes a string.
#include “stdio.h” int main(void) { char line[81] ; // for string storage gets(line); // whole line is the string printf(“Reversed line is\n”); print_reverse(line); // line is address return 0; }
10
print_reverse function
void print_reverse(char *s) //s is a string { char *ptr; ptr = s + strlen(s) - 1; // last char while ( ptr != s) // not start of string printf(“%c”, *ptr); // the character ptr--; // previous char } printf(“%c”, *ptr);// ptr == s // first character of s
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.