Chapter 5 Pointers and Arrays
Chapter 5 Pointers and Arrays
Chapter 5 Pointers and Arrays
p i
*
p
&i 5
Pointer variable
Pointer variable
int *p
Pointer variable
grammar * Pointer
variable
例示 *p
& and * operator
e.g. p=&i;
e.g. q=*p;
e.g. int a;
p=&a;
The
difference
between
“&*" and
"* &;"
What?
The following two statements are used to analyze the
difference between “&*" and "* &;". The operators
of "&;" and "*" have the same priority and are
combined from right to left. So "& * P" performs "*"
operation first, and "* P" is equivalent to variable a;
then "&;" operation, and "& * P" is equivalent to
taking the address of variable a. "* & a" performs
"&" operation first, and "&a" is to take the address of
variable a, and then "*" operation is to take the value
of the address of variable a, which is actually variable
a
指针的自增自减
指针自加自减运算
什么情况
指针自加自减运算
一维数组与指针
一维数组与指针
int *p,a[10];
例如 p=a;
int *p,a[10];
例如 p=&a[0];
一维数组与指针
一维数组与指针
Chapter 5 Pointers and Arrays
5.1 Pointers and Addresses
Declaration of a point:
type *namep;
Operate (two unary operators)
&: give the address of an object:
* (indirection or dereferencing operator): access
object
the A the pointer is constrained
pointer points to. to point to a
particular kind of object (variables, and array
Example:
elements). It cannot be applied to expressions,
int x=1,y=2,z[10];
constants, or register variables. A pointer to
intis
void *ip; /*ip isany
used to hold a poiter
type to
of int */
pointer.
ip=&x; /*ip now points to x */
y=*ip; /* y is now 1 */
*ip=0; /* x is now 0 */
ip=&z[0]; /*ip now points to z[0] */
Chapter 5 Pointers and Arrays
5.1 Pointers and Addresses
1000 20 x 1000 20 x
1002 1 y 1002 1 y
1004 155 z 1004 155 z
Example:
what are the values
that the variables contain?
int x=1, y=2; #include<stdio.h>
int main()
int *ip, *iq; {
ip=&x, iq=&y; int x=1, y=2;
int *ip, *iq;
*ip=*ip+10; ip=&x, iq=&y;
*ip=*ip+10;
y=*ip+1;
y=*ip+1;
++*ip; ++*ip;
(*ip)++;
(*ip)++; //*ip++;
*ip++; iq=ip;
printf("x=%d, y=%d\n", x,y);
iq=ip; printf("*ip=%d, *iq=%d", *ip, *iq);
return 0;
}
Chapter 5 Pointers and Arrays
5.2 Pointers and Function Arguments
a:
x:
b:
in caller:
y:
in swap:
Chapter 5 Pointers and Arrays
5.2 Pointers and Function Arguments
#include <ctype.h>
int getch(void);
void ungetch(int);
int getint(int *pn)
{ int c, sign;
while(isspace(c=getch())) /*skip white space */
;
if( !isdigit(c) && c!= EOF && c!=‘+’ && c!=‘-’) {
ungetch(c); /* it’s not number */
return 0;
}
sign = (c == ‘-’) ? -1:1;
if( c== ‘+’ || c==‘-’) c=getch();
for(*pn =0; isdigit( c); c=getch())
*pn=10* *pn +(c-’0’);
*pn *=sign;
if(c != EOF) ungetch(c);
return c;
}
Chapter 5 Pointers and Arrays
5.3 Pointers and Arrays
a:
a[0 a[1 a[2 a[9
pa:
] ] ] ]
int *pa;
pa=&a[0];
Chapter 5 Pointers and Arrays
5.3 Pointers and Arrays
int a[10]={10,9,8,7,6,5,4,3,2,1};
int *pa, x;
pa=&a[0]; /* or pa=a; */
x=*pa;
x=*(pa+2);
the name of an array is a
pa=&a[8]; synonym for the location of the initial
x=*pa; element, the assignment pa=&a[8] can
also be written as pa=a+8.
a: 10 9 8 7 6 5 4 3 2 1
a[0 a[1 a[2 a[9
pa:pa:
] ] ] ]
A pointer is a variable.1028 pa=a and
x
:
Equivalent form:
int strlen(char *s) int strlen(char s[ ])
{
int n;
for(n=0;*s!=‘\0’;s++)
n++;
return n;
}
strlen(“hello, world”); /* string constant */
strlen(array); /* char array[100]; */
strlen(ptr); /* char *ptr; */
Advantage:
can avoid large array’s pass.
Chapter 5 Pointers and Arrays
5.3 Pointers and Arrays
#include<stdio.h>
int strlen( char * );
int main( )
{
printf( "%d\n",strlen("hello, world") );
char array[100] = "Hello, World!!!";
printf("%d\n",strlen(array));
char * ptr = array;
printf( "%d\n", strlen(ptr) );
return 0;
}
int strlen( char *s )
{ int n;
for( n = 0; *s != '\0'; s++)
n++;
return n;
}
Chapter 5 Pointers and Arrays
5.4 Address Arithmetic
allocbuf:
in use free
allocbuf:
in use free
Chapter 5 Pointers and Arrays
5.4 Address Arithmetic
#include<stdio.h>
#include<stdlib.h> void *malloc(unsigned size)
int main() if((p=(int *)malloc(n*sizeof(int))){…
{ The main difference between malloc and
int n, sum, i, *p; calloc is that calloc will initialize the n
printf("Enter n:");
acquired memory units.
scanf("%d",&n);
if((p=(int *)calloc(n,sizeof(int))) == NULL){
printf("Not able to allocate memory.\n");
exit(1);
}
printf("Enter %d integers:", n);
for(i=0; i<n; i++)
scanf("%d",p+i);
sum=0;
for(i=0; i<n; i++)
sum=sum + *(p+i);
printf("The sum is %d \n",sum);
free(p);
return 0;
}
Chapter 5 Pointers and Arrays
5.4 Address Arithmetic
The behavior is undefined for arithmetic or
comparisons with pointer that do not point to
members of the same array .
defghi defghi
jklmnopqrst jklmnopqrst
abc abc
# include<stdio.h>
int main(void)
{
char *color[5]={"red", "blue", "yellow", "green",
"purple"};
int count=0, i, j;
char *temp;
temp = color[0];
color[0] = color[4];
color
color[4]=temp;
color[0] red\0
color
color[1] blue\0
color[2] yellow\0 color[0] red\0
Algorithm:
read all the lines of input
sort them
print them in order
Quicksort -- the fastest known sorting algorithm in practice
The Algorithm
void Quicksort ( ElementType A[ ], int N )
{
if ( N < 2 ) return;
pivot = pick any element in A[ ];
Partition S = { A[ ] \ pivot } into two disjoint sets:
A1={ aS | a pivot } and A2={ aS | a pivot };
A = Quicksort ( A1, N1) { pivot } Quicksort ( A2, N2);
}
13 43
81
31 57 26 65
13 81 92 75
0
92 43 65
31 57 26
0 13 26 31 43 57 65 75 81 92
75 0
0 13 26 31 43 57 65 75 81 92
1/15
Chapter 5 Pointers and Arrays
5.6 Pointer Arrays: Pointer to Pointer
# include<stdio.h>
#include <string.h>
#include<stdlib.h>
#define MAXLINES 5000
char *lineptr[MAXLINES];
int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);
void qsort(char *lineptr[], int left, int right);
/* sort input lines */
main()
{ int nlines; /* number of input lines read */
if((nlines=readlines(lineptr,MAXLINES))>=0) {
qsort(lineptr,0,nlines-1);
writelines(lineptr,nlines);
return 0;
}
else { printf("error: input too big to sort\n");
return 1; }
}
Chapter 5 Pointers and Arrays
5.6 Pointer Arrays: Pointer to Pointer
A[0][0] 1
Elements in a tow- A[0][1] 2
dimensional array are
A[1][0] 3
stored by rows/columns
A[1][1] 4
A[2][0] 5
A[2][1] 6
Chapter 5 Pointers and Arrays
5.7 Multi-Dimensional Arrays
Example:
char *name[ ]={“Illegal month”, “Jan”, ”Feb”, “Mar”};
char aname[ ][15] = {“Illegal month”, “Jan”, “Feb”, “Mar”};
name:
Illegal month\0
Jan\0
storage:26 bytes + 4 pointers
Feb\0
Mar\0
aname:
Illegal month\0 Jan\0 Feb\0 Mar\0
0 15 30 45
storage: 60 bytes
Chapter 5 Pointers and Arrays
5.10 Command-line Arguments
0
echo\0
argc is for argument count
and argv[ ] for argument hello,\0
vector. argv[argc] is a null world\0
pointer.
Chapter 5 Pointers and Arrays
5.10 Command-line Arguments
Example 2:
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
int getline(char *line, int max);
/*find: print lines that match pattern from 1st arg */
main(int argc, char *argv[])
{ char line[MAXLINE];
int found=0;
if( argc!=2) printf("Usage: find pattern\n");
else while (getline(line, MAXLINE)>0)
if(strstr(line, argv[1])!=NULL) {
printf(“**** %s ****", line);
found++;
}
return found; The pattern is specified by
} the first argument on the
command line.
Chapter 5 Pointers and Arrays
5.11 Pointers to Functions
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000 /*max lines to be sorted */
char *lineptr[MAXLINES]; /*pointers to text lines */
int readlines(char *lineptr[], int nlines);
void qsort(void *lineptr[], int left, int right, int (*comp)(void *, void *));
int numcomp(char *, char *);
/* sort input lines */
main(int argc, char *argv[])
{ int nlines; /* number of input lines read */
int numeric =0;/* 1 if numeric sort */
if(argc>1 && strcmp(argv[1], "-n")==0) numeric =1;
if((nlines = readlines(lineptr,MAXLINES)) >=0) {
qsort((void **)lineptr, 0, nlines-1,
(int (*) (void*, void*))(numeric?numcmp:strcmp));
writelines(lineptr,nlines);
return 0;
}else { printf(“input too big to sort\n”);
return 1; }
}
Chapter 5 Pointers and Arrays
5.11 Pointers to Functions