Introduction to pointers
(and strings, arrays revisited)
Strings
char name[ ] = “world”;
if (name == str) /* this compares just starting addresses*/
{
…;
}
2
11/22/2022
Strings
{
int j = 0;
while(s[j] != ‘\0’) ++j;
return j;
}
3
11/22/2022
Addresses and Pointers ( a brief)
4
11/22/2022
Pointers
5
11/22/2022
Pointers, an example
int *ip; /* ip is a pointer to int */
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] */
6
11/22/2022
1
x
1000
1000
ip
1024
Name
Value
Address
Pointer
*ip=*ip +10;
y= *ip +1 ;
(unary operator * and & bind more tightly than arithmetic operators.)
Pointers
main( )
{
int j = 10, k = 20;
swap(&j, &k);
printf(“%d %d”, j, k);
}
void swap(int *a, int *b)
{
int t;
t = *a, *a = *b, *b = t;
}
8
11/22/2022
Pointers and Arrays
int *ip;
ip = a;
ip[0] = 10; /* is same as a[0] = 10 */
*(ip + 5) = 20; /* same as ip[5] = 20 */
9
11/22/2022
strlen with pointers
{
int j = 0;
while(s[j] != ‘\0’) ++j;
return j;
}
10
11/22/2022
{
int j = 0;
while(*p != ‘\0’){ ++p;
++j;
}
return j;
}
String constants
#include<string.h>
main( )
{
int j, k;
char str[ ] = “hello world”;
char *p;
p = str; /* Ok */
p = “Hi is this right”;
j = strlen(p);
k = strlen(“how are you”);
}
11
11/22/2022
String Assignment
12
11/22/2022
strcpy
void strcpy(char *s, char *t)
{
*s = *t;
if(*t == ‘\0’) return;
while(*t !=’\0’) {
s++, t++;
*s = *t;
}
}
13
11/22/2022
A closer look
14
11/22/2022
String constant
15
11/22/2022
H | E | L | L | O | ‘\0’ |
1000 1001 1002 1004
/*this is perfectly correct */
strcpy revisited
{
while( (*s = *t ) != ‘\0’){
s++;
t++;
}
}
16
11/22/2022
{
int j=0;
while( (s[j] = t[j] ) != ‘\0’) j++;
}
{
while( *s++ = *t++ );
}