arrays, strings, & pointerscsce.uark.edu/~ahnelson/csce4114/lectures/lecture4.pdf · arrays,...

Post on 09-Aug-2020

27 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Arrays, Strings, & Pointers

Alexander Nelson

September 9, 2019

University of Arkansas - Department of Computer Science and Computer Engineering

Arrays, Strings, & Pointers

Arrays, Strings, & Pointers are all connected in C

• Pointer – Variable storing a memory location

• Array – Block of memory storing associated variables

Array identifier is a pointer to location of first element

• String – Array of character variables

1

Example

#include <stdio.h>

int main(){

char* myString1 = "Hello!\n";

char myString2[] = "Hello!\n";

printf("%s",myString1);

printf("%s",myString2);

return 0;

}

myString1 and myString2 are equivalent statements!

2

Pointers

Pointers

Pointer – Variable that points to a memory location

Requires:

• Name – Name of the pointer variable

• Type – Type of the variable that is being addressed, with

appended asterisk

e.g. int* myPointer;

Variable size in memory is not based on type, but on memory size

• Why?

3

Dereferencing Pointers

Pointer stores memory location – not value

Dereferencing – Obtaining value at a memory location

Dereference Operators:

• Unary Operator (*)

e.g. *myPtr = 5; //Dereferences myPtr and sets value to 5

• Bracket offset

e.g. myPtr[0] = 5; //Dereferences to value at

// myPtr+offset*sizeof(objective type)

4

Address of

Variable address accessed through ampersand (&) operator

Literally the “address of” the variable

Example:

int val = 5;

int* myPtr = &val;

//myPtr now is equal to memory location of val

5

Pointer Example

int val = 10;

int* myPtr = &val; //declare pointer to val

*myPtr = 5; //dereference pointer and set

//that location = 5

printf("val =%d",val);//print val=(value of val)

Output = ?

6

Objective Type

Objective Type – type of variable pointed at

e.g.

• int* p; //objective type = int

• int a[10]; //objective type = int

• int**p; //root objective type is int, objective type is int*

Incrementing pointer variable increments by size of objective type

e.g.

• Incrementing an int* increments value by sizeof(int)

• Incrementing an int** increments value by sizeof(int*)

7

Arrays

Arrays

Array – “an ordered series or arrangement”

C Array – Block of memory storing associated variables

• Accessed by same variable name

• Same data type

8

Declaration of Arrays

Arrays must be declared before use

Format:

type variable name[length]

• type – variable type of element to be stored

• variable name – identifier of the array

• length – number of elements to be stored

Declaration and definition of array reserves a block of memory

space according to type and length

9

Example Arrays

double height[10];

• type: double

• name: height

• length: 10 (memory size = 10×sizeof(double))

float width[30]; int c[9]; char name[20]; //string array

10

Array Implementation

Array identifier stores address of first element

Array identifier dereferenced by bracket operator obtains value

1st element stored at position 0, 2nd at 1, nth at (n-1)th element

e.g. a[n] = (n+1)th element

11

Array Initialization

Arrays should be initialized to some value

Uninitialized arrays are able to be accessed, & contain garbage

memory contents

Examples:

• int a[] = {10,20,30,40};• int a[5] = {1,2,3};

If array size > num initialized, all others initialized to 0

• int a[5] = {0};Shorthand to initialize all to 0

12

Accessing Array Elements

Accessed with a dereference operator and offset with [] operator

Can be read & modified like a normal variable

Valid Examples:

• c[0] = 3;

• c[3] += 5;

• y = c[x+1];

13

Multidimensional Arrays

Multidimensional arrays declared with each dimension

e.g. int array[3][2];

Initialize each column through comma separated curly brace

statements

e.g. int array[3][2] = {{1,2},{3,4},{5,6}};

Memory-wise, the above is equivalent to:

int array[6] = {1,2,3,4,5,6}

14

Shorthand multi-dimensional initialization

Rules:

Unspecified elements in given row – initialized to 0

Unspecified rows – initialized to 0

Examples:

• int array[3][2] = {{1},{3,4}} // == {1,0,3,4,0,0}• int array[3][2] = {{0}} // == {0,0,0,0,0,0}

15

Passing Arrays to Functions

Array identifier = pointer to first element

Identifier (memory address) is passed by value = reference to array

Array elements may be accessed by offset (known type)

Length of array is not known!

Use delimiter or pass length parameter(s)

16

Passing Array Elements

Array elements are passed by value!

Original memory location will not be modified

Example:

void myFunction(int a){

a = a+1;

return a;

}

int main(){

int array[5] = {0};

myFunction(array[0]);

printf("%d",array[0]); //Will print 0!

}

17

Function with Const Array

For arrays passed to functions with no intent to modify the array

const keyword before array parameter

e.g. int sum array(const int array[], int n);

Compiler will throw error for any element modification operations

18

What is the difference?

Identifier name points to first element

Pointer points to any element

Arithmetic operations on array name are disallowed

19

Example Difference

int g, grades[ ] = {10, 20, 30, 40 }, myGrade = 100;

int yourGrade = 85, *pGrades;

/* grades can be (and usually is) used as array name */

for (g = 0; g < 4; g++)

printf("%d\n",grades[g]);

/* grades can be used as a pointer to its array if it doesn’t change*/

for (g = 0; g < 4; g++)

printf(%d\n", *(grades + g));

/* but grades can’t point anywhere else */

grades = &myGrade; /* compiler error */

20

Example Continued

/* pGrades can be an alias for grades and used like an array name */

pGrades = grades; /* or pGrades = &(grades[0]); */

for( g = 0; g < 4; g++)

printf( "%d\n", pGrades[g]);

/* pGrades can be an alias for grades and be used like a pointer that changes */

for (g = 0; g < 4; g++)

printf("%d\n",*(pGrades++));

/* BUT, pGrades can point to something else other than the grades array */

pGrades = &myGrade;

printf( "%d\n", &pGrades);

pGrades = &yourGrade;

printf( "%d\n", &pGrades);

21

Array of Pointers

Pointers are a data type & can be placed in an array

e.g. ArrayList

Especially useful for array of variable string sizes to reduce wasted

bytes

e.g. char* myStringArray[] or char** myStringArray

22

Strings

Strings/Char Arrays

C doesn’t have a “string” type

Implemented using char arrays & “string literals”

To be a “string”, a char array must be null terminated

Example:

• char string1[] = “hello world!”;

• char string2[] = {’h’,’e’,’l’,’l’,’o’,’ ’,’w’,’o’,’r’,’l’,’d’,’ !’,’\0’};• char string3[5] = “hello”; //Error: 6 characters in string literal

• char string4[10] = “hello”; // “hello\0\0\0\0\0”

23

ASCII

American Standard Code for Information Interchange (ASCII)

• Encodes the Roman alphabet used in English/West European

languages

• Has 128 characters

• Encoded as leading 0 and 7 bit value

• Chars 0-31 represent control characters (e.g. “\n”)

C was designed to work with ASCII

The char data type is used to store ASCII characters in C

24

ASCII Table

Decimal Hex Char

Decimal Hex Char Decimal Hex Char Decimal Hex Char

25

Special Characters

Backslash character (“\”) used to indicate special character

e.g.

• \n – newline

• \t – tab

• \” – double quote

• \’ – single quote

• \\– backslash (since backslash has special meaning)

• \a – beep (unprintable)

26

Character Library

ctype.h – C library of char functions

Examples:

• int isdigit (int c) – Is c a decimal digit (‘0’ - ‘9’)?

• int isdigit(int c) – Is c a hexadecimal digit (‘0’ - ’9’, ‘a’ - f’, or

‘A’ - ‘F’)?

• int isalpha (int c) – Is c an alphabetic character (‘a’ - ‘z’ or

‘A- ‘Z’)?

• int isspace (int c) – Is c a whitespace character (space, tab,

etc)?

• int isprint (int c) – Is c a printable character?

• int tolower (int c) – Change c to lower case if alpha

• int toupper (int c) – Change c to upper case if alpha

27

String Output

Use %s in printf() or fprintf() to print string

Will print until NULL is seen

Can provide field width and justification

e.g.

char book1[] = “Dune”;

char book2[] = “Brave New World”;

printf(“Favorite Book: %12s”, book1);

printf(“Other Book: %12s”,book2);

What will the above print?

28

scanf()

scanf() – stdio function for taking input from stdin

Format: scanf(“%s”,string1);

• Reads characters from stdin until whitespace encountered

• Can write beyond end of array!

• Best case – “stack smashing detected”

• Worst case – Overwrites other memory

29

Example Program

#include <stdio.h>

int main(){

char string1[20], string2[]="string";

int i;

printf("Enter a string: ");

scanf("%s", string1);

printf("string1: %s\nstring2: %s\n",string1,string2);

for(i=0;string1[i]!=’\0’;i++)

printf("%c",string1[i]); // Print by iteration

printf("\n");

return 0;

}

30

scanf(“%#s”)

To avoid overflow, specify the number of characters!

char buffer[100] = ””;

scanf(”%99s”,buffer);

Why 99?

31

gets()/fgets()

gets(char* buffer) – read a line of input until ‘\n’

Newline then replaced with null character

Can overflow buffer!

fgets(char* buffer, int len, FILE *stream) – read a line of input

from file until n-1 characters or ‘\n’

Newline then replaced with null character

Safer, as max length can be specified! File can be STDIN

Returns NULL when EOF detected!

32

fgets() Example

FILE *inFile;

inFile = fopen( "myfile", "r" );

/* check that the file was opened */

char buffer[120];

while ( fgets(buffer, 120, inFile ) != NULL )

printf( "%s\n", string );

fclose( inFile );

Will read line-by-line up to 120 characters until EOF detected

33

sprintf()

Format a string in an array of characters

Akin to toString() in Java

sprintf() works like printf() but output goes to character array

e.g.

char buffer[100] = 0; int numStudents = 33;

sprintf(buffer,“There are %d students\n”,numStudents);

34

C String Library

string.h – C String library

Common string manipulation functions

e.g.

• strlen( const char string[ ] ) – Number of characters in string

(not including “null”)

• strcpy( char s1[ ], const char s2[ ] ) – Copies s2 on top of s1

• strcmp ( const char s1[ ] , const char s2[ ] ) – Returns < 0, 0,

> 0 if s1 < s2, s1 == s2 or s1 > s2 lexigraphically

• strcat( char s1[ ] , const char s2[ ]) – Appends (concatenates)

s2 to s1

35

C String Library

Some functions have size parameter

e.g.

• strncpy( char s1[ ], const char s2[ ], int n ) – Copies at most n

characters of s2 on top of s1

• strncmp ( const char s1[ ] , const char s2[ ], int n ) –

Compares up to n characters of s1 with s2 Returns < 0, 0, >

0 if s1 < s2, s1 == s2 or s1 > s2 lexigraphically

• strncat( char s1[ ], const char s2[ ] , int n) – Appends at most

n characters of s2 to s1

36

Array of Strings

Strings are arrays – Array of Strings == Multi-dimensional array

e.g.

char months[10][] = {“January”, “February”, “March”, “April”,

“May”, “June”, “July”, “August”, “September”, “October”,

“November”, “December”}; //120 byte array w/ 2 indices

37

Command Line Arguments

Command line arguments are passed to main as an array of strings

int main(int argc, char* argv[])

• argc – number of arguments

• argv – array of strings

• argv[0] – always the name of the executable

38

Pointer Arithmetic

Pointer Arithmetic

Incrementing a pointer increments by sizeof(objectiveType)

e.g.

char c, *cPtr = &c;

int i, *iPtr = &i;

float f, *fPtr = &f;

printf(“%p,%p%p”,cPtr++,iPtr++,fPtr++);

printf(“%p,%p%p”,cPtr++,iPtr++,fPtr++);

Outputs:

0x00, 0x10, 0x20

0x01, 0x14, 0x24

39

void Pointers

Void pointers are special case

C Standard does not allow arithmetic or dereferencing of void

pointers

However:

GCC has an extension that allows arithmetic

To dereference a void pointer, first cast to typed pointer, then

dereference

e.g. *(int *)myVoidPointer; (int)*myVoidPointer does not work!

40

Function Pointers

Function identifiers are a pointer to instruction memory

Can create a pointer to the instruction

Type == Return type of function

Also declared with parameters of function

e.g.

int myFunction(int param1);

int (*myFunctionPtr)(int) = &myFunction;

int ret = (*myFunctionPointer)(10);

41

top related