CSE13s Lecture 10 & 11

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/47

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

48 Terms

1
New cards

The size may be omitted if?

The array is initialized at the time of declaration.

<p><span><span>The array is initialized at the time of declaration.</span></span></p>
2
New cards

Strings in C are?

Character arrays that end with a ‘\0’ (NULL) character.

3
New cards

\0’ is an “end-of-string” marker?

Used to determine the end of a string.

4
New cards

In (C) if you make a string the null terminator count as an item.

"Power" then you could do char type[6] = "Power"

5
New cards

Initialization cannot be separated from the declaration!

char str[5]; str = “good”; is not permitted

6
New cards

Strings can be read using scanf()

Format specifier: %s

7
New cards

scanf() terminates its input?

On the first white space it finds!

Use multiple char arrays: char adr1[5], adr2[5]; scanf(“%s %s”, adr1, adr2);

8
New cards

Syntax: scanf(“%[...]”, variable);

Example: scanf(“%[abc]”, str) accepts strings containing only a, b, and c

○ Example: scanf(“%[^xyz]”, str) accepts strings that exclude x, y and z

○ Example: scanf(“%[^\n]”, str) accepts a string (including spaces) until a new-line

9
New cards

char line[10];

line[0] = getchar();

You’re reading one character from input (the terminal).
If you want to read an entire line (a string), you must:

  1. Loop to read characters one at a time until a newline '\n' is entered,

  2. Store each character in the array, and

  3. Manually add a null terminator ('\0') at the end.

<p>You’re reading <strong>one character</strong> from input (the terminal).<br>If you want to read an entire <strong>line (a string)</strong>, you must:</p><ol><li><p><strong>Loop</strong> to read characters one at a time until a newline <code>'\n'</code> is entered,</p></li><li><p><strong>Store</strong> each character in the array, and</p></li><li><p><strong>Manually add a null terminator (</strong><code>'\0'</code><strong>)</strong> at the end.</p></li></ol><p></p>
10
New cards

gets()?

gets() reads chars into a string until new-line is encountered and then appends a null

character to the string

○ char line[10]; gets(line); but it wont stop if you pass your array size

11
New cards

putchar()?

Prints one character at a time:

char ch = ‘A’; putchar(ch);

Can Not do a whole string at a time unless you implement a for loop.

12
New cards

puts()?

Prints an entire string and moves the cursor to the next line:

char line[10]; puts(line);

13
New cards

C does not allow direct assignment of strings?

char str[5]; str = “good”; is not permitted

char s1[4] = “abc” ; char s2[4]; s2 = s1; is not permitted

14
New cards

Copy one string into another?

  1. Char-by-char.

  2. As a whole using the strcpy function.

15
New cards

Does C allow joining two strings together by simple arithmetic addition?

No

16
New cards

Does C permit the comparison of two strings directly?

No

  1. Compare the strings character by character.

  2. Use the strcmp() function.

17
New cards
strcpy(s2, s1)

Purpose:

Copy all characters from s1 (including '\0') into s2

What happens if destination is too small:

Buffer overflow — will overwrite memory past s2

What happens if source is too small:

Works fine (copies full string + null)

Notes:

Must ensure s2strlen(s1) + 1

18
New cards
strncpy(s2, s1, n)

Purpose:

Copy up to n characters from s1 to s2

What happens if destination is too small:

If n > s2 size → overflow possible

What happens if source is too small:

If strlen(s1) < n, fills rest of s2 with '\0'

Notes:

Does not add '\0' if s1 length ≥ n

19
New cards
strcat(s1, s2)

Purpose:

Append s2 to end of s1

What happens if destination is too small:

Overwrites memory if s1 is too small to hold result

What happens if source is too small:

Works fine

Notes:

Make sure s1 has enough space for both strings + '\0'

20
New cards
strncat(s1, s2, n)

Purpose:

Append up to n chars from s2 to s1

What happens if destination is too small:

Overflow if s1 can’t hold strlen(s1) + n + 1

What happens if source is too small:

Works fine

Notes:

Always adds '\0' at end

21
New cards
strcmp(s1, s2)

Purpose:

Compare full strings (Alphabetically)

What happens if destination is too small:

Safe (no writing)

What happens if source is too small:

Safe

Notes:

Returns 0 if equal, <0 or >0 otherwise

22
New cards
strncmp(s1, s2, n)

Purpose:

Compare first n characters

What happens if destination is too small:

Safe

What happens if source is too small:

Safe

Notes:

Same return logic as strcmp

str1 == str2

Both strings are identical

0

"apple" vs "apple"0

str1 < str2

str1 comes before str2 alphabetically

Negative

"apple" vs "banana"< 0

str1 > str2

str1 comes after str2 alphabetically

Positive

"pear" vs "orange"> 0

23
New cards
strlen(s)

Purpose:

Count characters until '\0'

What happens if destination is too small:

If string lacks '\0', runs past valid memory

What happens if source is too small:

Safe if string is valid

Notes:

Doesn’t include null terminator in count

24
New cards
strstr(src, sub)

Purpose:

Find substring inside another

What happens if destination is too small:

Safe (read-only)

What happens if source is too small:

Safe

Notes:

Returns pointer to first match or NULL

25
New cards
gets(str) ⚠️ Unsafe, deprecated

Purpose:

Reads input line until newline

What happens if destination is too small:

May overflow if input > array size

What happens if source is too small:

Works fine if space allows

Notes:

Use fgets() instead

26
New cards
scanf("%s", str)

Purpose:

Reads word until space

What happens if destination is too small:

May overflow if input > array size

What happens if source is too small:

Works fine

Notes:

Use width limit: scanf("%9s", str) for a 10-char buffer

27
New cards

User-defined data types?

  1. typedef

  2. enum

  3. struct

  4. union

  5. bitfield

28
New cards

Typedef?

  1. Allows users to create new data type names for existing data types

  2. Can create meaningful data type names to increase readability of the program

  3. typedef unsigned int uint; uint val = 25;

29
New cards

Enum?

Unique types with values ranging over a set of named constants starting at 0 by default

30
New cards

Structures

Collection of one or more related variables, possibly of different types, grouped

together under a single name for convenient handling

Example: typedef struct book_bank {

char title[20];

int pages;

float price[3];

struct {char first_name[20], char last_name[20]} author;

} book_bank;

<p>Collection of one or more related variables, possibly of different types, grouped</p><p>together under a single name for convenient handling</p><p></p><p>Example: typedef struct book_bank {</p><p>char title[20];</p><p>int pages;</p><p>float price[3];</p><p>struct {char first_name[20], char last_name[20]} author;</p><p>} book_bank;</p>
31
New cards

Arrays of structures

Example: book_bank books[3] contains 3 instances of book_bank structure

○ Accessing each book: books[0], books[1] and books[2]

32
New cards

Copying and comparing structure variables

Two variables of the same structure type can be copied the same way as primitive vars

○ Example: book1 = book2;

However, logical operations are not permitted on structure variables

○ Example: book1 == book2 is not permitted;

To compare two variables, we compare the individual members

○ book1.pages == book2.pages;

○ strcmp(book1.title, book2.title)

33
New cards

Difference Between Struct and Union

A struct stores all its members separately, each with its own memory space.

A union stores all its members in the same memory location.
Only one member is valid at a time — changing one affects the others.

34
New cards

Bit fields

struct Status {

unsigned int power_on : 1; // 1 bit (0 or 1)

unsigned int error_code : 3; // 3 bits (0–7)

unsigned int mode : 2; // 2 bits (0–3)

};

35
New cards

Pointers are extremely useful as they allow us to

return multiple values from a function

 manage dynamic memory (heap) and, thereby, dynamic data structures like linked lists

 refer to functions and thereby facilitate passing of functions as arguments to other functions

36
New cards

Declaring pointers

datatype *pt_name;

○ * tells the compiler that pt_name is a pointer variable

○ Upon initialization or assignment, pt_name contains a memory address

○ pt_name points to a variable of type data_type

37
New cards

Different declaration styles

The following 3 styles are equivalent

○ int* p //clear

○ int * p

○ int *p

38
New cards

Pointer operations

○ Get the address of a variable using & operator and store in a pointer variable

○ Dereference a pointer variable to get to something using * operator

○ Compute the address of something (since a pointer is an integer)

39
New cards

We can increment or decrement pointers

p1 = p1 + 1, where p1 is a pointer

40
New cards

Pointer to a pointer

int x, p1, *p2 ;

// p1 is a pointer to an int; int*

// p2 is a pointer to an int*; int**

x = 10; p1 = &x; p2 = &p1;

41
New cards

the value at index i

*(p + i) == x[i]

42
New cards

(*(p+1) + j)

points to the jth row in the second row

43
New cards

Accessing elements with the pointer:

int (*p)[4];

int a[3][4] = {

{10, 20, 30, 40},

{50, 60, 70, 80},

{90, 100, 110, 120}

};

*p

first row (a[0])

*(p+1)

second row (a[1])

*(p+2)

third row (a[2])

*(*(p+1) + 2)

element in row 1, column 2 (a[1][2])

44
New cards

p

Row 0

p + 1

Row 1

*(p + 1)

First element of row 1

*(p + 1) + j

j-th element of row 1

*(*(p + 1) + j)

Value at a[1][j]

int (*p)[4]

Pointer to a row of 4 ints

int *p[4]

Array of 4 int pointers

45
New cards

Pointers and strings

char *str = “good”;

46
New cards

Pointers to structures and unions

Consider the struct: typedef struct {

int x;

int y;

} vector;

● If we declare, vector v, *ptr; ptr = &v;

○ Here, ptr is a pointer pointing to the vector v.

○ We can access its elements using the . or -> operators

■ Using indirection: (*ptr).x

■ Using arrow operator: ptr->x

47
New cards

type (*fptr) ();

  • int (*fptr)(int, int); → pointer to a function that takes two ints and returns int.

  • int *fptr(int, int); → function that takes two ints and returns a pointer to int.

48
New cards

Common errors using pointers

p = m;

assigning value, not address

p = &m;

printf("%d", p);

prints address, not value

printf("%d", *p);

*p = m;

p not initialized

p = &var; *p = m;

p = &m; (uninit m)

may read garbage

initialize m first

if(p > q)

comparing unrelated pointers

only compare within same array