Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Pointer and Arrays

What is a pointer
Pointers
A pointer is a variable that contains the address of a variable. They are
commonly used in C because they are sometimes the only way to express a
computation and partly because they usually lead to more compact and
efficient code than can be obtained any other way
Pointers and Addresses
MEMORY
CHAR
BYTE

SHORT INT
2 BYTES

LONG INT
4 BYTES
Pointers and Addresses
Pointers and Addresses
int x = 1, y =2, z[10];

int *ip; /*ip is 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] */


Pointers and Function Arguments
Pointers and Function Arguments
void swap(int a, int b){ /* the wrong way to do it */
int temp;
temp = a;
a = b;
b = temp;
printf("%d and %d", a, b);
}
Pointers and Function Arguments
void swap(int *pa, int *pb){
int temp; //temporary variable
temp = *pa;
*pa = *pb;
*pb = temp;
printf("%d and %d", *pa, *pb); //now we just want to see
what it’s pointing to
}
Full code
#include <stdio.h> void swap(int *pa, int
void swap(int *pa, int *pb){
*pb); int temp;
main(){ //temporary variable
int pa = 10; temp = *pa;
int pb = 11; *pa = *pb;
swap(&pa, &pb); *pb = temp;
} printf("%d and %d", *pa,
*pb); //now we just want to
see what its pointing to
}
Pointers and Function Arguments
Pointers and Arrays
Pointers and Arrays
In C there is a strong relationship between pointers and arrays,strong enough
that pointers and arrays should be discussed simultaneously. Any operation
that can be achieved y array subscripting can be done with pointers, but faster
Pointers and Arrays
Pointers and Arrays
#include <stdio.h>
int strlen(char *s);
main(){
char s[] = "hello";
printf("%d", strlen(s));
}//strlen: return length of string s
int strlen(char *s){
int n;
for (n = 0; *s != '\0'; s++) {
n++;
}
return n;
}
Other concepts to look at
More to look at
● Address arithmetic
● Character pointers and functions
● Pointer Arrays: Pointers to Pointers
● Multi - dimensional Arrays
● Complicated declarations
● Pointer functions
● etc

You might also like