arrays in c - binghamtontbartens/cs211_fall_2017/lectures/l10...•sizeof calculates the number of...

37
Binghamton University CS-211 Fall 2017 Arrays in C 1

Upload: phamkhuong

Post on 08-Apr-2018

217 views

Category:

Documents


2 download

TRANSCRIPT

Binghamton

University

CS-211

Fall 2017

Arrays in C

1

Binghamton

University

CS-211

Fall 2017

One Dimensional Array (Vector)

• Ordered List of Values

• All of the same type

• Individual elements accessible by “index”

• Vector has a Size (Number of elements)

2

0 1 2 3 4 5

17.3 14.5 3.2 12.0 5.65 14.5

Binghamton

University

CS-211

Fall 2017

Why Use a Vector?

• When your data is a list of values

• For instance, gates per chip

int gpc[12];

gpc[0]=gpc[1]=gpc[3]=4;

gpc[2]=6;

gpc[4]=gpc[5]=gpc[8]=3;

gpc[6]=gpc[7]=2;

gpc[9]=1;

gpc[10]=gpc[11]=4;

3

0 1 2 3 4 5 6 7 8 9 10 11

4 4 6 4 3 3 2 2 3 1 4 4

Binghamton

University

CS-211

Fall 2017

One Dimensional Array Declaration

type name[size];

• type - Any built-in or derived data type• int, char, short, float, etc.

• name - Any valid variable name• e.g. vx, vy, myArray, etc. etc.

• size - Integer constant - how many items are in the list

• Vectors must be declared before they are used.

4

Binghamton

University

CS-211

Fall 2017

Vector Size

• Number of elements

int vec[12]; // Reserve space for 12 integers

• WARNING: Indexes are 0,1,2,3,…, 9, 10, 11!• Index starts at 0

• Index ends at (SIZE-1)

• To find the size of an array: sizeof(vec)/sizeof(int)• sizeof calculates the number of bytes needed for a variable or type

• In the above example, sizeof(vec)=36, sizeof(int)=14

5

Binghamton

University

CS-211

Fall 2017

Referencing Vector Values

name[index]

• name - The (declared) name of a vector

• index - The index of a specific element in the vector• “First” element in the vector is vec[0]

• “Last” element in the vector is vec[size-1]

• Index may be any valid integer expression• e.g. : vec[3], vec[j], vec[2*i+1]

6

Binghamton

University

CS-211

Fall 2017

Example Vector Code

int grades[14];

… // Code which fills in grades goes here

int j,sum=0;

for(j=0; j<14; j++) {

sum +=grades[j];

}

float avg=(float)sum/14.0;

printf(“Average grade: %f\n”,avg);

7

Binghamton

University

CS-211

Fall 2017

Initializing a Vector

int x=7; // Initializing a scalar variable

int gpc[12]={4,4,6,4,3,3,2,2,3,1,4,4}; // Initializing vector

• Or, let the compiler count the number of elements

int gpc[ ]= {4,4,6,4,3,3,2,2,3,1,4,4};

8

0 1 2 3 4 5 6 7 8 9 10 11

4 4 6 4 3 3 2 2 3 1 4 4

Binghamton

University

CS-211

Fall 2017

Array Declaration with Initialization

type name[size] = { list_of_constants }

• Each constant separated by a comma

• If size specified, and list is too short, padded to the right with zeroes

• If size is not specified, size is number of elements in list

• IF ARRAY IS NOT INITIALIZED IT’S INITIAL VALUE IS UNKNOWN!• Whatever value was in memory when the functions starts

9

Binghamton

University

CS-211

Fall 2017

Matrix – Two Dimensional Array

• Declaration: type name[rows][cols];

• Reference: name[row_index][col_index]• 0 <= row_index < rows

• 0 <= col_index < cols

• Indexes may be any integer expressions

10

Binghamton

University

CS-211

Fall 2017

Why Use a Matrix?

• When your data is rectangular in nature

• For example, Grades for Multiple Students• Each student takes one row

• Each grades takes one column

11

Student Quiz1 Homework1 Test1 Homework2 …

John Smith 98 76 68 82 …

Alice Jones 73 94 86 79 …

Jane Jameson 62 73 68 70 …

… … … … …

Binghamton

University

CS-211

Fall 2017

Example Matrix Code

int grades[20][14]; // Space for 20 students, 14 grades

int st;

for(st=0;st<20;st++) {

int gr; int sum=0;

for(gr=0;gr<14;gr++) sum+=grades[st][gr];

printf(“Average for student %2d: %f\n”,st,sum/14.0);

}

12

Binghamton

University

CS-211

Fall 2017

Array Dimensions

Vector: int vec[4]={10,20,30,40};

Matrix: int matrix[2][3]={10,11,12,20,21,22}

Cube: char cube[3][2][3] = { “abcdefghijklmnopqr”};

13

vec[0] vec[1] vec[2] vec[3]

10 20 30 40

matrix[0][0]10

matrix[0][1]11

matrix[0][2]12

matrix[1][0]20

matrix[1][1]21

matrix[1][2]22

[0][0][0]‘a’

[0][0][1]‘b’

[0][0][2]‘c’

[0][1][0]‘d’

[0][1][1]‘e’

[0][1][2]‘f’

[1][0][0]‘g’

[1][0][1]‘h’

[1][0][2]‘i’

[1][1][0]‘j’

[1][1][1]‘k’

[1][1][2]‘l’

[2][0][0]‘m’

[2][0][1]‘n’

[2][0][2]‘o’

[2][1][0]‘p’

[2][1][1]‘q’

[2][1][2]‘r’

Binghamton

University

CS-211

Fall 2017

Array Bounds Checking

int vec[5]; int i;

for(i=0;i<=5;i++) vec[i]=4;

• NO RUN-TIME ARRAY BOUNDS CHECKING IN C!!!!!!!!!!!!

• Trust the programmer, and save the run-time!

• Programmer must be trustworthy!

• Writing past the end of an array can cause many problems• May write over other variables• May cause a segmentation violation

14

vec[0]4

vec[1]4

vec[2]4

vec[3]4

vec[4]4

i4

Binghamton

University

CS-211

Fall 2017

Array Values are “Contiguous”

• Right next to each other in memory

• int vec[6]

• int m [4][3];

• If we know where the first element is, we know the entire array!

15

vec[0] vec[1] vec[2] vec[3] vec[4] vec[5]

m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] m[3][0] m[3][1] m[3][2]

Binghamton

University

CS-211

Fall 2017

“Row Major Order”• Think of multi-dimensional indexes as an odometer…

• Rightmost digit of index increases the fastest

• Once rightmost digit reaches it’s limit, it goes back to zero, and

• Digit to the left increases by 1

int m[4][3]={0,1,2,10,11,12,

20,21,22,30,31,32};

16

m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] m[3][0] m[3][1] m[3][2]

0 1 2 10 11 12 20 21 22 30 31 32

0 1 2

0 0 1 2

1 10 11 12

2 20 21 22

3 30 31 32

Binghamton

University

CS-211

Fall 2017

Array “Types”

• “Type” tells the compiler how to interpret a value• int, float, char, etc.

• An array has a “type” – tells the compiler how to read the array• Includes the number of dimensions

• Includes the size of each dimension

• Includes the type of each element

• For instance, to declare a parameter which is a vector:

int sum(int grades[17]) { …

Binghamton

University

CS-211

Fall 2017

Arrays as Pointers

• We will learn more about pointers later

• “*” in a declaration is used to indicate “is a pointer to”• int * x; // means x is a pointer to a character

• double * f; // means f is a pointer to a double precision floating point number

• In C, a vector is very similar to a pointer to a list of elements

• In fact, C lets us use EITHER pointer OR array notation

Binghamton

University

CS-211

Fall 2017

Arrays and Pointers

Using an Array as a pointer

int grades[17];int * grdPtr=grades;printf(“grades at %x\n”,grdPtr);

Using a pointer as an array

int sum(int * grdPtr) {

int j,sum=0;

while(grdPtr[j]>0) {

sum+=grdPtr[j++];

}

return sum;

}

Binghamton

University

CS-211

Fall 2017

Incomplete Array Sizes

• In some cases, C allows first dimension to have unspecified size

int vec[ ]• vec is an list of some number of integers…

• Programmer must know how many elements are usable!• Must map to a fully specified array before it is used

int mat[ ][4];• mat is an array in which each row has 4 integers• Programmer must know how many rows are usable

20

vec[0] vec[1] vec[2] vec[3] vec[4] …

Binghamton

University

CS-211

Fall 2017

Variable Sized Array Example

int sumVec(int s, int vec[ ]) {int j; int sum=0;

for(j=0;j<s;j++) {

sum+=vec[j];

}

return sum;

}

int main() {int vec1[3] = { 1,3,5 };int vec2[5] = { 1,1,1,1,1 };if (sumVec(3,vec1) <

sumVec(5,vec2)) {printf(“vec2 sum is bigger\n”);

}return 0;

}

21

Binghamton

University

CS-211

Fall 2017

Strings in C

22

Binghamton

University

CS-211

Fall 2017

What is a “string”?

• A “string” is just a vector of ASCII characters• Followed by a “null terminator” – a byte with the value 0 or 0x00

• Warning: blanks in ASCII have a non-zero value (0x20)

char str[14]=“This a string”;

23

Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13

ASCII T h i s a s t r i n g

Hex x54 x68 x69 x73 x20 x61 x20 x73 x74 x72 x69 x6e x67 x00

{‘T’, ’h’, ’i’, ’s’, ’ ‘, ’a’, ’ ‘, ’s’, ’t’ ,’r’ ,’i’ ,’n’ ,’g’, x00}

Binghamton

University

CS-211

Fall 2017

The “null terminator”

• A null terminator is a single byte with the value 0b00000000• A null terminator is NOT a null address… not NULL!

0b00000000_00000000_00000000_00000000• A null terminator is NOT an integer 0

0b00000000_00000000_00000000_00000000

• When we assign a word 0 to a char 0, the left bits are truncated• So we can assign 0 to a char to get a null terminator

• When we compare a null-terminator to a word 0, the null terminator is extended to word length

• So we can compare a byte to 0 to see if it is a null terminator

• To avoid confusion, I use 0x00 as a null terminator (0b00000000)• You will also see ‘\0’ – the ASCII escaped null terminator (0b00000000)

Binghamton

University

CS-211

Fall 2017

Using Pointer Notation

• We already learned that C lets us use pointer notation for arrays

int * c3; // is very similar to int c3[]

• When dealing with strings, we almost always use pointer notation • Length is not important BECAUSE we have a null terminator

char * string; // is very similar to char string[]

Binghamton

University

CS-211

Fall 2017

Pointer notation and Memory

• Pointer notation does NOT reserve space for a string!

char * string;

string[0]=0x00; // results in SEGMENTATION VIOLATION!

• A literal string DOES reserve space for the literal string

char * string=“This is a test”; // string points to literal

string[0]=‘X’; // Modify the literal in memory

printf(“String is: %s\n”,string);

// prints String is: Xhis is a test

Binghamton

University

CS-211

Fall 2017

printf substitutes string for %s

char str[14]=“This a string”;

printf(“Variable str contains | %s | and no more\n”,str);

Variable str contains | This a string | and no more

27

Binghamton

University

CS-211

Fall 2017

Empty String

char str[14]=“This a string”;

str[0]=x00;

printf(“Variable str contains |%s| and no more\n”,str);

Variable str contains || and no more

28

Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13

ASCII h i s a s t r i n g

Hex x00 x68 x69 x73 x20 x61 x20 x73 x74 x72 x69 x6e x67 x00

Binghamton

University

CS-211

Fall 2017

Standard Library String Functions

#include <string.h>

char str[18]=“This a string”;

printf(“Size of str buffer: %d\n”,sizeof(str));

printf(“Length of str string: %d\n”,strlen(str));

Size of str buffer: 18

Length of str string: 13

29

Indx 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

char T h i s a s t r i n g ∅ ∅ ∅ ∅ ∅

Hex x54 x68 x69 x73 x20 x61 x20 x73 x74 x72 x69 x6e x67 x00 x00 x00 x00 x00

Binghamton

University

CS-211

Fall 2017

strlen(char str[ ]);

• Returns the number of bytes up to (but not including) the null terminator of the argument string.

• Because we start indexes at zero:str[strlen(str)]==0x00 // ALWAYS TRUE!

char empty[20]=“”;printf(“Length of empty: %d\n”,strlen(empty));Length of empty: 0

30

Binghamton

University

CS-211

Fall 2017

strcpy(char to[ ],char from[ ])

• Copies “from” string to “to” string

• ASSUMES “to” is large enough to hold strlen(from)

char buf[100]=“Old string“;

char new[20]=“Newer string”;

strcpy(buf,new);

printf(“Variable buf contains | %s | and no more\n”,buf);

Variable buf contains | Newer string | and no more

31

Binghamton

University

CS-211

Fall 2017

strcat(char start[ ],char tail[ ])

• Copies “tail” string at the end of “start” string

• ASSUMES “start” is large enough to hold both “start” and “tail”

char start[100]=“Beginning “;

char end[20]=“of a test.”;

strcat(start,end);

printf(“Variable start contains | %s | and no more\n”,start);

Variable start contains | Beginning of a test. | and no more

32

Binghamton

University

CS-211

Fall 2017

strncat(char start[ ],char tail[ ],int n)

• Copies up to n bytes of “tail” string at the end of “start” string

• ASSUMES “start” is big enough to hold both start and n bytes of tail

• Safer than strcat

char start[100]=“Beginning “;

char end[20]=“of a test.”;

strncat(start,end,6);

printf(“Variable start contains | %s | and no more\n”,start);

Variable start contains | Beginning of a t | and no more33

Binghamton

University

CS-211

Fall 2017

To be totally safe….

strncat(start,end,sizeof(start)-strlen(start));

34

Binghamton

University

CS-211

Fall 2017

strcmp(char a[ ], char b[ ])

• Compares the string in “a” to the string in “b”• If a<b, returns a number less than zero

• If a==b, returns zero

• If a>b, returns a number greater than zero

• Cannot compare strings with ==, <, >, <=, etc. operators!• Can compare CHARACTERS with ==, <, …

if (0==strcmp(name,”Tom”)) printf(“Hi Tom…”);

35

Binghamton

University

CS-211

Fall 2017

strncmp(char a[], char b[],int n)

• Compares the string in “a” to the string in “b” for up to n characters• If a<b, returns a number less than zero

• If a==b, returns zero

• If a>b, returns a number greater than zero

• Cannot compare strings with ==, <, >, <=, etc. operators!• Can compare CHARACTERS with ==, <, …

if (0==strncmp(name,”Tom”,3))

printf(“Name starts with Tom…”);

36

Binghamton

University

CS-211

Fall 2017

Resources

• Programming in C, Chapter 6 (Arrays)

• Programming in C, Chapter 9 (Strings)

• Wikipedia C String Handlinghttps://en.wikipedia.org/wiki/C_string_handling

• C String Tutorial : http://www.tutorialspoint.com/cprogramming/c_strings.htm

37