# Pointers

Document Sample

```					  Arrays, Pointers, Strings

Lecture 18
19/2/2002

Sudeshna Sarkar, CSE, IIT
19-Feb-02              Kharagpur             1
Pointer arithmetic and
element size

double a[2], * p, *q ;
p=a;                 /*points to base of array*/
q=p+1;               /*  q=&a[1]             */
printf(“%d\n”, q-p);             /* 1 printed */
printf(“%d\n”, (int)q - (int)p); /* 8 printed */

Sudeshna Sarkar, CSE, IIT
19-Feb-02                  Kharagpur                    2
Arrays as function arguments
 In a function definition, a formal parameter that
is declared as an array is actually a pointer.
 When an array is passed as an argument to a
function, the base address of the array is
passed “call by value”. The array elements are
not copied.
double sum (double a[], int n) { double sum (double *a, int n) {
int i; double sum;
int i; double sum;
for (i=0,sum=0.0; i<n; i++)
for (i=0,sum=0.0; i<n; i++)
sum += a[i];                             sum += a[i];
return sum;
return sum;
}
Sudeshna Sarkar, CSE, IIT
}19-Feb-02                      Kharagpur                              3
Recursively finding the
sum

double sum (int a[], int n) {
if ( n == 0 ) return 0 ;
return a[0] +
sum (a+1, n-1) ;
}
Sudeshna Sarkar, CSE, IIT
19-Feb-02            Kharagpur             4
Various ways that sum() might be
called

What gets computed
Invocation               and returned

sum(v,20)                 v[0]+…+v[19]

sum(v,10)                 v[0]+…+v[9]

sum(&v[7],3)              v[7]+v[8]+v[9]

sum(v+2,10)               v[2]+…+v[11]
Sudeshna Sarkar, CSE, IIT
19-Feb-02                       Kharagpur                  5
Recursive programs using arrays
int sum (int a[], int size) {
if (size==0) return 0;
return a[0]+sum(a+1,size-1);
}
void reverse (int a[], int size) {
if (size==0 || size==1)
return;                           could have written
swap2 (&a[0], &a[size-1]);                swap2(a,a+size-1);
reverse (a+1,size-2);
}
Sudeshna Sarkar, CSE, IIT
19-Feb-02                   Kharagpur                             6
Recursive programs using arrays
int * binsearch (int elem, int a[], int size) {
if (size==0) return NULL;
mid = size/2;
if (elem == a[mid]) return &a[mid];
if (elem > a[mid]) {
return binsearch (elem, a+mid+1, size-mid-1);
}
else return (elem, a, mid);
}

Sudeshna Sarkar, CSE, IIT
19-Feb-02                   Kharagpur                      7
Recursive programs using arrays
void remove (char c, char s[]) {
void shiftleft (char s[]) {
char * p;                                 int i;
if (s[0]==‘\0’) return;                   for (i=0; s[i] !=‘\0’;i++)
if (s[0] == c) {                          {
shiftleft (s);                        s[i] = s[i+1];
}
remove (c, s);
}
}
else
remove (c, s+1);
}
Sudeshna Sarkar, CSE, IIT
19-Feb-02                   Kharagpur                                 8
Strings
 1-d arrays of type char
 By convention, a string in C is terminated by the
end-of-string sentinel \0 (null character)
 char s[21] - can have variable length delimited
with \0.
 Max length is 20 as the size must include
storage needed for the delimiter.
 String constants : “hello”, “abc”
 “abc” is a character array of size 4.
Sudeshna Sarkar, CSE, IIT
19-Feb-02                Kharagpur                9
Strings

A string constant is treated as a pointer. Its
value is the base address of the string.
char *p = “abc”;      p        a b c \0
printf (“%s %s\n”,p,p+1); /* abc bc is printed */

Sudeshna Sarkar, CSE, IIT
19-Feb-02                Kharagpur                    10
Differences : array & pointers

char *p = “abcde”;                   char s[] = “abcde”;
The compiler allocates                char s[] = {‘a’,’b’,’c’,’d’,’e’.’\0’};
space for p, puts the              The compiler allocates 6 bytes
string constant “abcde”               of memory for the array s
in memory somewhere                   which are initialized with the
elese, initializes p with             6 characters.
string constant.
p
s
a b c d e \0                           a b c d e \0
Sudeshna Sarkar, CSE, IIT
19-Feb-02                        Kharagpur                                11
A program using strings
/* Count the number of words in a string */
#include <ctype.h>
int word_cnt (char s[]) {
int cnt = 0, i;
for (i=0; s[i] != ‘\0’) {
while (isspace(s[i]))                /* skip white space */
++i;
if (s[i] != ‘\0’) {                  /* found a word     */
++cnt;
while (!isspace(s[i]) && s[i]!=‘\0’) /* skip the word */
++i;
}
}
return cnt;
Sudeshna Sarkar, CSE, IIT
}
19-Feb-02                           Kharagpur                             12
The program with pointers
/* Count the number of words in a string */
#include <ctype.h>
int word_cnt (char *s) {
int cnt = 0;
while (*s != ‘\0’) {
while (isspace(*s))                /* skip white space */
++s;
if (*s != ‘\0’) {                  /* found a word     */
++cnt;
while (!isspace(*s) && *s!=‘\0’) /* skip the word */
++s;
}
}
return cnt;
Sudeshna Sarkar, CSE, IIT
}
19-Feb-02                          Kharagpur                           13
String-handling functions in
the standard library
 #define string.h
 char *strcat (char *s1,
char *strcat(char *s1, const char *s2)
const char *s2);
{
 Takes 2 strings as          char *p = s1;
arguments,                  while (*p) /* go to the end */
concatenates them, and           ++p;
puts the result in s1.      while (*p++ = *s2++) /* copy */
Returns s1.                      ;
Programmer must             return s1;
ensure that s1 points to }
enough space to hold
the result.
Sudeshna Sarkar, CSE, IIT
19-Feb-02                     Kharagpur                      14
Dissection of the strcat() function
char *p = s1;
p is being initialized, not *p. The pointer p is initialized to the
pointer value s1. Thus p and s1 point to the same memory
location.
while (*p) ++p; /*  while (*p != ‘\0’) ++p; */
As long as the value pointed to by p is non-zero, p is
incremented, causing it to point at the next character in the
string. When p points to \0, the expression *p has the value
0, and control exits the while statement.
while (*p++ = *s2++) ;
At the beginning, p points to the null character at the end of
string s1. The characters in s2 get copied one after another.
Sudeshna Sarkar, CSE, IIT
19-Feb-02                      Kharagpur                              15
int strcmp (const char *s1, const char *s2);

Two strings are passed int strcmp(char *s1, char *s2) {
as arguments. An         for (;*s1!=‘\0’&&*s2!=‘\0’; s1++,s2++)
integer is returned      {
that is less than,             if (*s1>*s2) return 1;
equal to, or greater           if (*s2>*s1) return -1;
than 0, depending on      }
whether s1 is             if (*s1 != ‘\0’) return 1;
lexicographically less    if (*s2 != ‘\0’) return -1;
than, equal to, or        return 0;
greater than s2.       }

Sudeshna Sarkar, CSE, IIT
19-Feb-02                   Kharagpur                     16
char *strcpy (char *s1, const char *s2);
The characters is the string s2 are copied into s1 until \0 is
moved. Whatever exists in s1 is overwritten. It is
assumed that s1 has enough space to hold the result.
The pointer s1 is returned.
size_t strlen (const char *s);
A count of the number of characters before \0 is returned.

size_t strlen (const char *s) {    char * strcpy (char *s1, char *s2) {
size_t n;                         char *p = s1;
for (n=0; *s!=‘\0’; ++s)          while (*p++ = *s2++) ;
++n;                          return s1;
return n;                      }
}
Sudeshna Sarkar, CSE, IIT
19-Feb-02                      Kharagpur                           17
Examples of string handling
functions
char s1[] = “beautiful big sky country”,
s2[] = “how now brown cow”;
Expression                  Value
strlen (s1)
strlen (s2+8)
strcmp(s1,s2)
Statements                  What gets printed
printf(“%s”,s1+10);
strcpy(s1+10,s2+8);
strcat(s1, “s!”);
printf(“%s”, s1);
Sudeshna Sarkar, CSE, IIT
19-Feb-02                   Kharagpur             18
Examples of string handling
functions
char s1[] = “beautiful big sky country”,
s2[] = “how now brown cow”;
Expression                Value
strlen (s1)                25
strlen (s2+8)               9
strcmp(s1,s2)              negative integer
Statements                 What gets printed
printf(“%s”,s1+10);        big sky country
strcpy(s1+10,s2+8);
strcat(s1, “s!”);
printf(“%s”, s1);          beautiful brown cows!
Sudeshna Sarkar, CSE, IIT
19-Feb-02                  Kharagpur               19

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 2 posted: 2/25/2012 language: pages: 19