[go: up one dir, main page]

0% found this document useful (0 votes)
22 views33 pages

IP-08-Advanced Pointer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views33 pages

IP-08-Advanced Pointer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Advanced pointer

Inst. Nguyễn Minh Huy

Fundamentals of Programming - Nguyễn Minh Huy 1


Contents
 String manipulations.
 Pointer of pointer.
 Other types of pointers.

Fundamentals of Programming - Nguyễn Minh Huy 2


Contents
 String manipulations.
 Pointer of pointer.
 Other types of pointers.

Fundamentals of Programming - Nguyễn Minh Huy 3


String manipulations
 Dynamic C string:
 Array of chars + ‘\
‘\0’.
 Dynamic string = pointer + memory management.

char *s1 = new char[6]; s1 27 ? ? ? ? ? ?


char *s2 = new char[ ] { “hello” }; }; s2 49 h e l l o \0
char *p = s2;
s2;
int len1 = strlen
strlen(( p ); // len1 = 5
int len2 = strlen
strlen(( p + 2 ); // len2 = 3 p p+2
//…
delete [ ]s1;
delete [ ]s2;

Fundamentals of Programming - Nguyễn Minh Huy 4


String manipulations
 Iterate C string:
 Use index:
for ( int i = 0; s[ i ] != ‘\
‘\0’
0’;; ++i
++i )
{
// Process character s[ i ].
}
 Use pointer:
for ( char *p = s; *p != ‘\
‘\0’; ++p )
{
// Process character *p.
}

Fundamentals of Programming - Nguyễn Minh Huy 5


String manipulations
 Copy string:
 Do not use “=“.
char s1[ ] { “Hello” }; s1 27 H e l l o \0

char *s2 = s1;


s1; s2 27 // Memory conflict!

 Two--step copy: strcpy


Two strcpy(( <
<dest
dest>,
>, <source> ).
 Step 1: allocate new string.
 Step 2: copy string content.

char s1[ ] = “Hello”; s1 27 H e l l o \0

char *s2 = new char[ strlen


strlen(s1)
(s1) + 1 ]; s2 94 H e l l o \0
strcpy(( s2, s1 );
strcpy

Fundamentals of Programming - Nguyễn Minh Huy 6


String manipulations
 Copy string:
 One--step copy:
One
 strdup( <source string> ).
strdup(
 Return: new string copied from source string.
 New string must be de-
de-allocated by free
free().
().
char s1[ ] { “Hello” };
char *s2
*s2 = strdup
strdup(( s1 );

// Same as….
// char *s2
*s2 = new char[ strlen
strlen(( s1 ) + 1 ];
// strcpy
strcpy(( s2, s1 );

free(( s2 );
free

Fundamentals of Programming - Nguyễn Minh Huy 7


String manipulations
 Compare string:
 strcmp( <string 1>, <string 2> ).
strcmp(
 Return: 0 (equal), 1 (greater), -1 (less).
 Compare based on dictionary order.
char s1[ ] { ““abc
abc”” };
char s2[ ] { ““abaab
abaab”” };
char s3[ ] { ““Abc
Abc”” };

int r1 = strcmp
strcmp(( s1, s2 ); // r1 = 1.
int r2 = strcmp
strcmp(( s3, s1 ); // r2 = -1.
int r3 = strcasecmp
strcasecmp(( s3, s1 ); // r3 = 0, GCC compiler.
int r4 = stricmp
stricmp(( s3, s1 ); // r4 = 0, MSVC compiler.

Fundamentals of Programming - Nguyễn Minh Huy 8


String manipulations
 Join string:
 strcat( <
strcat( <dest
dest>,
>, <source> ).
 Copy source to the end of dest
dest..
 Dest string must have enough memory!!
char s1[ ] { “Hello” };
char s2[ ] { “World” };
int len1 = strlen
strlen(( s1 );
int len2 = strlen
strlen(( s2 );
char *s3
*s3 = new char[ len1 + len2 + 1 ];

strcat( s3, s1 );
strcat( // Join s1 to s3.
strcat(( s3, s2 );
strcat // Then, join s2 to s3.
// More efficient way…
strcpy(( s3, s1 );
strcpy
strcpy(( s3 + len1, s2 );
strcpy

Fundamentals of Programming - Nguyễn Minh Huy 9


String manipulations
 Find sub char/string:
 strchr( <source>, <sub> ).
strchr(
 strstr(( <source>, <sub> ).
strstr
 Return: pointer to sub in source or NULL (not found).
// Find and skip to find all t in s.
char s[ ] { “the cat the dog” };
char t [ ] { “the” };

int len = strlen


strlen(( t );
for ( char *p = s; (p
(p = strstr
strstr(( p, t ) ); p += len )
printf(( “Found at %d
printf %d\\n”, p – s );
s 49 t h e c a t t h e d o g \0

p p + len p p + len

Fundamentals of Programming - Nguyễn Minh Huy 10


String manipulations
 Find any of char in/not in set:
 strpbrk(( <source>, <set> ).
strpbrk
 Return: pointer to first source char in set or NULL (not found).
 strspn(( <source>, <set> ).
strspn
 Return: distance to first source char not in set.
// Find and skip to find all any of t in s.
char s[ ] { “15 cats 30 dogs” };
char t [ ] { “0123456789” };

for ( char *p = s; (p
(p = strpbrk
strpbrk(( p, t ) ); p += strspn(
strspn( p, t ) )
printf(( “Found at %d
printf %d\\n”, p – s );
s 49 1 5 c a t s 3 0 d o g s \0

p p + strspn(
strspn( p, t ) p p + strspn(
strspn( p, t )

Fundamentals of Programming - Nguyễn Minh Huy 11


String manipulations
 Convert string to number:
 To integer:
 atoi( <string> )
atoi(
 strtoll(( <string>, <end pointer>, <base> ).
strtoll
 To float:
 atof( <string> ).
atof(
 strtod(( <string>, <end pointer> ).
strtod
char s1[
s1[ ] { “123abc” };
char s2[
s2[ ] { “xyz” };
int x1 = atoi
atoi(( s1 ); // x1 = 123
int x2 = atoi
atoi(( s2 ); // x2 = 0
char *p;
int y1 = strtoll
strtoll(( s1, &p, 10 ); // y1 = 123, p = “abc
“abc””
int y2 = strtoll
strtoll(( s2, &p, 10 ); // y2 = 0, p = “xyz”

Fundamentals of Programming - Nguyễn Minh Huy 12


String manipulations
 Input dynamic string:
 Declare struct Student:
 Id: fix-
fix-sized 8 chars.
 Name: variable-
variable-sized 50 chars.
 GPA: float.
 Write function to input a student from keyboard.

Fundamentals of Programming - Nguyễn Minh Huy 13


Contents
 String manipulations.
 Pointer of pointer.
 Other types of pointers.

Fundamentals of Programming - Nguyễn Minh Huy 14


Pointer of pointer
 Address of pointer:
 Variable has an address.
 int has address int *.
 Pointer also has an address.
 int * has address type?
 Pointer of pointer:
 A variable stores address of another pointer.
 Declaration: <pointer type> * <pointer name>;

Fundamentals of Programming - Nguyễn Minh Huy 15


Pointer of pointer
 Pointer of pointer in C:
 Declaration:
 Method 1: use *.
 Method 2: use typedef
typedef..
 Initialization:
 Use NULL
NULL..
 Use & operator. 72 73 74 75
int x = 257; x 1 1 0 0
int *p = NULL
NULL;;
44 45 46 47
int **q
**q = NULL
NULL;;
p 72 0 0 0

p = &x; 96 97 98 99
q = &p; q 44 0 0 0

Fundamentals of Programming - Nguyễn Minh Huy 16


Pointer of pointer
 Pointer of pointer in C:
 Access memory content: void foo
foo((int **g,
**g, int **&h)
**&h)
 1-level access: operator *. {
(**g)++; (*g)++; g++;
 2-level access: operator **.
**.
(**h)++; (*h)++; h++;
 Passing argument: }
 Pass-by-
Pass- by-value.
int main()
 Pass--by-
Pass by-reference. {
int a[10];
int *p = a;
 Which values are int **q = &p;
changed in foo()
foo() ? int **r = &p;

foo(
foo(q, r);
r);
}

Fundamentals of Programming - Nguyễn Minh Huy 17


Pointer of pointer
 Dynamic matrix:
 Array of pointers:
 Level-1 pointer is 1
Level- 1--dimensional dynamic array.
 Level--2 pointer is 2
Level 2--dimensional dynamic array.

void inputMatrix
inputMatrix((int **&m**&m,, int &rows
&rows,, int &cols
&cols)) {
printf(( “Enter rows and cols = “);
printf
scanf(“%d
scanf (“%d %d”, &rows, &cols); int main()
{
m = new int * [ rows ]; int **m;
**m;
for (int
(int i = 0; i < rows; i++) { int rows, cols;
m[ i ] = new int [ cols ];
for (int
(int j = 0; j < cols; j++) inputMatrix(m,
inputMatrix (m, rows, cols);
scanf(“%d”,
scanf (“%d”, &&m[
m[ i ][ j ]);
]); delete [ ]m;
} // Error!! How to fix?!
} }

Fundamentals of Programming - Nguyễn Minh Huy 18


Contents
 String manipulations.
 Pointer of pointer.
 Other types of pointers.

Fundamentals of Programming - Nguyễn Minh Huy 19


Other types of pointers
 Constant pointer:
 Pointer points to only 1 address “for life”.
 Declaration: <type> * const <pointer name>;
int x = 5, y = 6;
int * const p = &x;
p = &y; // Wrong.
 All static arrays in C are constant pointers.
 Pointer to constant:
 Memory content pointer points to cannot be changed.
 Declaration: const <type> * <pointer name>;
int x = 5;
const int *p = &x;
*p = 6; // Wrong.
Fundamentals of Programming - Nguyễn Minh Huy 20
Other types of pointers
 void pointer:
 Pointer can store address of any types.
 Declaration: void * <pointer name>.
 Cast to specific type when accessing content.

void printBytes
printBytes((void *p, *p, int size) int main()
{ {
char *q = ( unsigned char * ) p; int x = 1057;
for ( int i = 0; i < size; i++ ) double y = 1.25;
printf(( “%d “, q[ i ] );
printf
} printBytes(&x, 4);
printBytes(&x,
printBytes(&y,
printBytes (&y, 8);
}

Fundamentals of Programming - Nguyễn Minh Huy 21


Other types of pointers
 Function pointer:
 Function address:
 Functions are also stored in memory.
 Each function has an address.
 Function pointer stores address of function.
 Declaration:
<return type> (* <pointer name>)
name>) (<arguments>);
(<arguments>);
typedef <return type> (* <alias>
<alias>)) (<arguments>);
(<arguments>);
<alias> <pointer name>;
 Functions have same address type if:
 Same return type.
 Same arguments.

Fundamentals of Programming - Nguyễn Minh Huy 22


Other types of pointers
 Function pointer:
typedef int (*Operator
(*Operator)(
)(int
int a, int b); int main()
{
int add
add((int u, int v) int x = 5;
{ int y = 6;
return u + v;
} Operator p = add add;;
int mul
mul((int u, int v) int r1 = p(x, y);
{
return u * v; p = mul
mul;;
} int r2 = p(x, y);
int calculate
calculate((int u, int v, Operator p)
{ // u3 operator v2. int r3 = calculate
calculate(x,
(x, y, add
add);
);
return p(u*u*u, v*v); }
}

Fundamentals of Programming - Nguyễn Minh Huy 23


Other types of pointers
 Pointer to fix-
fix-sized memory:
 Address of static array:
 What address type of static array?
int a[ 10 ];
int *p = a // p and a store address of a[ 0 ].
??? q = &a;
 Pointer to fix-
fix-sized memory:
 Pointer stores address of static array.
 Declaration:
<array type> (*<pointer
(*<pointer name>)[
name>)[<array
<array size>]
size>];
int a[ 10 ];
int ( *p )[ 10 ] = &a; // p points to 10-
10-element array.

Fundamentals of Programming - Nguyễn Minh Huy 24


Other types of pointers
 Pointer to fix-
fix-sized memory:
 Static 2-
2-D array in C:
 Is pointer to fix-
fix-sized 1-
1-D array.
 Stores address of the first row.
int a[ 2 ] [ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int ( *p )[ 3 ] = a; // a = &a[ 0 ].
printf(“%d
printf (“%d\\n”, *( *(p
*(p + 1)
1) + 1 ) );
a[0][0] a[0][1] a[0][2]
44 45 46 47 72 73 74 75 76 77 78 79 80 81 82 83
p 72 0 0 0 a[0] 1 0 0 0 2 0 0 0 3 0 0 0
a[1][0] a[1][1] a[1][2]
84 85 86 87 88 89 90 91 92 93 94 95
a[1] 4 0 0 0 5 0 0 0 6 0 0 0

p+1 *(p + 1) + 1

Fundamentals of Programming - Nguyễn Minh Huy 25


Other types of pointers
 Pointer to fix-
fix-sized memory:
 Passing static 2-
2-D array to function:
 Not passing whole array.
 Only passing address of first row.
void printMatrix
printMatrix((int a[ ][20],
][20], int rows, int cols) { // pass &a[ 0 ].
for (int
(int i = 0; i < rows; i++) {
for (int
(int j = 0; j < cols; j++)
printf(“%d
printf (“%d “, a[ i ][ j ] );
printf(“
printf (“\\n”);
}
}
int main() {
int a[10][20];
printMatrix((a, 10, 20);
printMatrix
}

Fundamentals of Programming - Nguyễn Minh Huy 26


Summary
 String manipulations:
 Dynamic string = pointer + memory management.
 Copy string: strcpy
strcpy,, strncpy.
strncpy.
 Join string: strcat (not efficient).
 Compare string: strcmp
strcmp,, strcasecmp,
strcasecmp, stricmp.
stricmp.
 Find sub char/string: strchr
strchr,, strstr.
strstr.
 Find any of char in/not in set: strpbrk
strpbrk,, strspn.
strspn.
 Convert to number: atoiatoi,, strtoll,
strtoll, atof,
atof, strtof.
strtof.
 Types of pointers:
 Different types  different address types.
 Each address type stored by one pointer type.
Fundamentals of Programming - Nguyễn Minh Huy 27
Summary
 Types of pointers:
 Pointer of pointer  stores address of pointer.
 Constant pointer  stores constant address.
 Pointer to constant  stores address of constant.
 void pointer  stores address of any types.
 Function pointer  stores address of function.
 Pointer to fix-
fix-sized memory  stores address of static
array.

Fundamentals of Programming - Nguyễn Minh Huy 28


Practice
 Practice 8.1:
Write C/C++ program to find and replace all as follow:
- Enter a sentence of words S.
- Enter word to find F, and replacing word R.
- Find and replace all F in S with R.
- Print the result sentence.
Input format:
Enter a sentence = the good, the bad, the ugly
Enter find word = the
Enter replacing word = (a very)
Output format:
(a very) good, (a very) bad, (a very) ugly

Fundamentals of Programming - Nguyễn Minh Huy 29


Practice
 Practice 8.2:
Write C/C++ program to increase numbers in sentence as follow:
- Enter a sentence.
- Find all numbers in the sentence and increase each one to 1.
- Print the result sentence.
Input format:
Enter a sentence = there are 9 cats and 19 dogs.
Output format:
there are 10 cats and 20 dogs.

Fundamentals of Programming - Nguyễn Minh Huy 30


Practice
 Practice 8.3:
Write C/C++ program to input a paragraph with arbitrary length:
- Enter a long paragraph until input ‘.’ and new line.
- Print the paragraph.
Note: use dynamic string.

Fundamentals of Programming - Nguyễn Minh Huy 31


Practice
 Practice 8.4:
Given static 2-
2-D array as follow:
int m[4][6];
What types of addresses of the following variables?
a) m[1][3].
b) m[0].
c) m.
Write code to access m[2][4] without using operator [ ].

Fundamentals of Programming - Nguyễn Minh Huy 32


Practice
 Practice 8.5:
Given the following C code:
void initialize
initialize(double
(double **p) int main()
{ {
for (int
(int i = 0; i < 5; i++) double *p[10];
initialize(p
initialize (p + 3);
*(p + i) = new double[ i + 1 ];
release(p);
release (p);
}
}
Answer the following questions:
a) How many bytes are allocated
at each line of main( ) ?
b) How memory are allocated by
initialize( ) function in main( ) ?
c) Write release( ) function
to avoid memory leak.

Fundamentals of Programming - Nguyễn Minh Huy 33

You might also like