W20-Strings

W20-Strings - Strings (and Things) 11/14/05 1 Arrays of...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
11/14/05 1 Strings (and Things) 11/14/05 2 Arrays of characters Consider char c[11] = {'c','h','a','r','s','t', 'r','i','n','g','s'}; c c h a r s t r i n g s 11/14/05 3 Strings Consider printf("%s", "charstrings"); c h a r s t r i n g s \0 '\0' has numerical value 0. It's called the null character .
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
11/14/05 4 Null Pointer vs. Character • Don't confuse these two NULL = null pointer = address (4 bytes) with value zero. It's a constant defined in <stdio.h>. Returned by fopen() when error. '\0' = null character = character (1 byte) with value zero. Used as last character of a string to indicate it's end. 11/14/05 5 Strings have null termination • The character '\0' (null character) terminates every string (ASCII value 0). • The purpose is to delimit (i.e. mark) the end of the string. • This allows functions (like printf()) to process strings without knowing length ahead of time. 11/14/05 6 Strings = Arrays of chars A string is a null character terminated array of characters. The value of a string is the address of it’s first character! • Thus a constant string functions as a constant pointer.
Background image of page 2
11/14/05 7 Strings and Pointers • Initialization in declaration char a[] = "xyz"; char a[] = {'x', 'y', 'z', '\0'}; /* same thing */ char *p = "xyz"; /* pointer initialization */ • Assignment char *p; p = "xyz"; /* p points to 'x' */ 11/14/05 8 No automatic copy in C char a[50], *p, b[] = "abcdef"; p = b; /* OK, assignment of address*/ p = "xyz"; /* OK, addr. assignment again */ a[] = b[]; /* NO! doesn't work */ a = b; /* NO! a is a constant */ 11/14/05 9 string declaration and memory p a b c \0 pa char *p; char *p = "abc"; char a[3]; char a[] = "abc"; a b c \0 ???
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 10

W20-Strings - Strings (and Things) 11/14/05 1 Arrays of...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online