• No se han encontrado resultados

lect04

N/A
N/A
Protected

Academic year: 2020

Share "lect04"

Copied!
41
0
0

Texto completo

(1)

Introduction to C

Pointers and Arrays

Instructor: Yin Lou

(2)

Pointers

I A pointer is a variable that contains the address of a variable

I Pointers are powerful but dangerous as well

I Sometimes pointers are the only way to express the computation

I Points usually lead to more compact and efficient code

I But the programmer must be extremely careful

(3)

Pointers

I A pointer is a variable that contains the address of a variable

I Pointers are powerful but dangerous as well

I Sometimes pointers are the only way to express the computation

I Points usually lead to more compact and efficient code

(4)

Memory

I Variables are stored in memory

I Think of memory as a very large array

I Every location in memory has an address

I An address is an integer, just like an array index

I In C, a memory address is called a pointer

I C lets you access memory locations directly

(5)

Two Operators

I & (“address of”) operator

I Returns the address of its argument

I Said another way: returns apointerto its argument

I The argument must bea variable name.

I * (“dereference”) operator

I Returns the value stored at a given memory address

(6)

Declaration

int i; // Integer i

int *p; // Pointer to integer int **m; // Pointer to int pointer

p = &i; // p now points to i

printf("%p", p); // Prints the address of i (in p)

m = &p; // m now points to p

printf("%p", m); // Prints the address of p (in m)

(7)

Example

int a = 0; int b = 0; int *p;

a = 10; p = &a;

*p = 20; // a = ? b = ?

p = &b;

(8)

Passing Pointers to Functions

void swap(int *a, int *b) {

int t = *a; *a = *b; *b = t; }

void main() {

int a = 5, b = 3;

printf("Before swap: a = %d b = %d\n", a, b); swap(&a, &b);

printf("After swap: a = %d b = %d\n", a, b); }

(9)

Multiple Return Values

void initialize(int *a, char *b) {

*a = 10; *b = ’x’; }

void main() {

int a, b;

(10)

Pointers Are Dangerous

What does this code do?

void main() {

char *x; *x = ’a’; }

What about this code?

void main() {

char x = ’a’; char *p = &x; p++;

printf("%c\n", *p); }

(11)

Pointers Are Dangerous

What does this code do?

void main() {

char *x; *x = ’a’; }

What about this code?

void main() {

char x = ’a’; char *p = &x; p++;

(12)

Arrays

I To declare an array, use [], e.g:

I int a[5]; // Creates an array with 5 integer elements

I The size of an array can’t be changed

I The number between the brackets must be a constant

I You can give initial values for array elements, e.g:

I int a[5] ={3, 7, -1, 4, 6};

I A better way: int a[] ={3, 7, -1, 4, 6}; // Let the compiler calculate the size

(13)

Arrays

I To declare an array, use [], e.g:

I int a[5]; // Creates an array with 5 integer elements

I The size of an array can’t be changed

I The number between the brackets must be a constant

I You can give initial values for array elements, e.g:

I int a[5] ={3, 7, -1, 4, 6};

(14)

Arrays

I To declare an array, use [], e.g:

I int a[5]; // Creates an array with 5 integer elements

I The size of an array can’t be changed

I The number between the brackets must be a constant

I You can give initial values for array elements, e.g:

I int a[5] ={3, 7, -1, 4, 6};

I A better way: int a[] ={3, 7, -1, 4, 6}; // Let the compiler calculate the size

(15)

Arrays

I To declare an array, use [], e.g:

I int a[5]; // Creates an array with 5 integer elements

I The size of an array can’t be changed

I The number between the brackets must be a constant

I You can give initial values for array elements, e.g:

I int a[5] ={3, 7, -1, 4, 6};

(16)

Arrays

I To declare an array, use [], e.g:

I int a[5]; // Creates an array with 5 integer elements

I The size of an array can’t be changed

I The number between the brackets must be a constant

I You can give initial values for array elements, e.g:

I int a[5] ={3, 7, -1, 4, 6};

I A better way: int a[] ={3, 7, -1, 4, 6}; // Let the compiler calculate the size

(17)

Arrays

I To declare an array, use [], e.g:

I int a[5]; // Creates an array with 5 integer elements

I The size of an array can’t be changed

I The number between the brackets must be a constant

I You can give initial values for array elements, e.g:

I int a[5] ={3, 7, -1, 4, 6};

(18)

Arrays

I Array indices in C are zero-based, e.g. a[0], a[1], ..., a[4]

Example

void main() {

int a[] = {3, 7, -1, 4, 6}; int i;

double mean = 0;

// compute mean of values in a for (i = 0; i < 5; ++i) {

mean += a[0]; }

mean /= 5;

printf("Mean = %.2f\n", mean); }

(19)

Arrays

I Array indices in C are zero-based, e.g. a[0], a[1], ..., a[4]

Example

void main() {

int a[] = {3, 7, -1, 4, 6}; int i;

double mean = 0;

// compute mean of values in a for (i = 0; i < 5; ++i) {

mean += a[0]; }

(20)

Pointers and Arrays

I Pointers and arrays are closely related

I An array variable is actually just a pointer to the first element

in the array

I You can access array elements using array notation or pointers

I a[0] is the same as *a

I a[1] is the same as *(a + 1)

I a[2] is the same as *(a + 2)

(21)

Pointers and Arrays

I Pointers and arrays are closely related

I An array variable is actually just a pointer to the first element in the array

I You can access array elements using array notation or pointers

I a[0] is the same as *a

I a[1] is the same as *(a + 1)

(22)

Pointers and Arrays

I Pointers and arrays are closely related

I An array variable is actually just a pointer to the first element in the array

I You can access array elements using array notation or pointers

I a[0] is the same as *a

I a[1] is the same as *(a + 1)

I a[2] is the same as *(a + 2)

(23)

Pointers and Arrays

I Pointers and arrays are closely related

I An array variable is actually just a pointer to the first element in the array

I You can access array elements using array notation or pointers

I a[0] is the same as *a

I a[1] is the same as *(a + 1)

(24)

Pointers and Arrays

I Accessing array elements using pointers

Example

void main() {

int a[] = {3, 7, -1, 4, 6}; int i;

double mean = 0;

// compute mean of values in a for (i = 0; i < 5; ++i) {

mean += *(a + i) }

mean /= 5;

printf("Mean = %.2f\n", mean); }

(25)

Pointers and Arrays

I If pa points to a particular element of an array, (pa + 1)

always points to the next element, (pa + i) points i elements

after pa and (pa - i) points i elements before.

I The only difference between an array name and a pointer:

I A pointer is a variable, so pa = a and pa++ is legal

(26)

Pointers and Arrays

I If pa points to a particular element of an array, (pa + 1)

always points to the next element, (pa + i) points i elements

after pa and (pa - i) points i elements before.

I The only difference between an array name and a pointer:

I A pointer is a variable, so pa = a and pa++ is legal

I An array name is not a variable, so a = pa and a++ is illegal

(27)

Strings

I There is no string type in C!

I Instead, strings are implemented as arrays of characters: char

* or char []

I Enclosed in double-quotes

I Terminated by NULL character (’\0’)

I ”Hello”

I printf format: %s

I same as

(28)

Strings

I There is no string type in C!

I Instead, strings are implemented as arrays of characters: char

* or char []

I Enclosed in double-quotes

I Terminated by NULL character (’\0’)

I ”Hello”

I printf format: %s

I same as

char str[] ={’H’, ’e’, ’l’, ’l’, ’o’, ’\0’}

(29)

Strings

I There is no string type in C!

I Instead, strings are implemented as arrays of characters: char

* or char []

I Enclosed in double-quotes

I Terminated by NULL character (’\0’)

I ”Hello”

I printf format: %s

I same as

(30)

Built-in String Functions

I string.h has functions for manipulating null-terminated strings,

e.g.

I strlen(char *s): returns length of s

I strcat(char *s1, char *s2): appends s2 to s1 (s1 must have enough space!)

I strcpy(char *s1, char *s2): copies s2 into s1(Again, s1 must have enough space!)

I strcmp(char *s1, char *s2): compares s1 and s2

(31)

Built-in String Functions

I string.h has functions for manipulating null-terminated strings,

e.g.

I strlen(char *s): returns length of s

I strcat(char *s1, char *s2): appends s2 to s1 (s1 must have enough space!)

I strcpy(char *s1, char *s2): copies s2 into s1(Again, s1 must have enough space!)

(32)

Pointers, Arrays and Functions

I It’s possible to pass part of an array to a function, by pass a pointer to the beginning of the subarray.

I f(&a[2])

I f(a + 2)

I Within f, the parameter declaration can read

I f(int arr[]){ ... }

I f(int *arr){ ... }

(33)

Pointers, Arrays and Functions

I It’s possible to pass part of an array to a function, by pass a pointer to the beginning of the subarray.

I f(&a[2]) I f(a + 2)

I Within f, the parameter declaration can read

I f(int arr[]){ ... }

(34)

Pointers, Arrays and Functions

I It’s possible to pass part of an array to a function, by pass a pointer to the beginning of the subarray.

I f(&a[2]) I f(a + 2)

I Within f, the parameter declaration can read

I f(int arr[]){ ... }

I f(int *arr){ ... }

(35)

Example

int strlen(char *s) {

int n = 0;

while (*s != ’\0’) {

s++; n++; }

return n; }

(36)

Dynamically Allocating Arrays

I malloc: Allocate contiguous memory dynamically

I int *p = (int *) malloc(n * sizeof(int));

I An array of size n

I free: Deallocate the memory

I free(p);

I Make sure malloc and free are paired!

(37)

Dynamically Allocating Arrays

I malloc: Allocate contiguous memory dynamically

I int *p = (int *) malloc(n * sizeof(int));

I An array of size n

I free: Deallocate the memory

I free(p);

(38)

Dynamically Allocating Arrays

I malloc: Allocate contiguous memory dynamically

I int *p = (int *) malloc(n * sizeof(int));

I An array of size n

I free: Deallocate the memory

I free(p);

I Make sure malloc and free are paired!

(39)

Dynamically Allocating Arrays

I malloc: Allocate contiguous memory dynamically

I int *p = (int *) malloc(n * sizeof(int));

I An array of size n

I free: Deallocate the memory

I free(p);

(40)

Dynamically Allocating Arrays

I malloc: Allocate contiguous memory dynamically

I int *p = (int *) malloc(n * sizeof(int));

I An array of size n

I free: Deallocate the memory

I free(p);

I Make sure malloc and free are paired!

(41)

Dynamically Allocating Arrays

I malloc: Allocate contiguous memory dynamically

I int *p = (int *) malloc(n * sizeof(int));

I An array of size n

I free: Deallocate the memory

I free(p);

Referencias

Documento similar

• El verbo “to be” es el primer tema de la unidad I que conforma el PAI (programa académico institucional) de la materia de conversaciones introductorias en lengua

Our results here also indicate that the orders of integration are higher than 1 but smaller than 2 and thus, the standard approach of taking first differences does not lead to

In short, websites are a communication tool that must be consistent with the institutional aims, must contribute to the transmission of information, and especially have to attract

The estimation for the Ginzburg-Landau parameter κ = 0.14 obtained from ARPES and STS data indicates that SrPd 2 Ge 2 is likely to be a type-I superconductor. But

Phases of Solar system formation: Formation of planets and small bodies in the protoplanetary disk.. IAC Winter School

In this work we have shown that, when applied to SVM training, Rosen’s gradient projection method can be written under closed formulae that lead to a simple and

The morphology of the density of states calculated by DFT for both compounds shows a more efficient conduction process in polymer [Cu(HIN)I] n , and the 3D orbital isodensities

An alternative explanation to the sensors lead time might be that hashtags are more likely to be created by the most active users such as the ones in the sensor group, and that,