t14ACharactersAndStringVariables Pps
t14ACharactersAndStringVariables Pps
CSCI 230
Dale Roberts
Fundamentals of Strings and Characters
Characters
Building blocks of programs
Every program is a sequence of meaningfully grouped characters
Character constant
An int value represented as a character in single quotes
'z' represents the integer value of z
Strings
Series of characters treated as a single unit
Can include letters, digits and special characters ( *, /, $)
String literal (string constant) - written in double quotes
"Hello"
Strings are arrays of characters
String a pointer to first character
Value of string is the address of first character
Dale Roberts
Fundamentals of Strings and Characters
String declarations
Declare as a character array or a variable of type char *
char color[] = "blue";
char *colorPtr = "blue";
Remember that strings represented as character arrays
end with '\0'
color has 5 elements
Inputting strings
Use scanf
scanf("%s", word);
Copies input into word[]
Do not need & (because a string is a pointer)
Remember to leave room in the array for '\0'
Dale Roberts
Character Pointers
String constant acts like a character pointer
char *pc = ABCDE; /* declare a character pointer variable */
Dale Roberts
Character Pointers
CONSTANT MEMORY
Example: s2
AREA (READ ONLY)
800 1100
100 100 a
char s1[] = abc;
char *s2 = abc; s1[] 101 b
1000 a
f() 102 c
{ 1001 b 103 \0
s1[1] = y; /* OK */ 1002 c
s2[1] = y; /* wrong (PC is OK)*/ 104 t
1003 \0
s1 = test; /* wrong */
105 e
s2 = test; /* OK */
} 106 s
Example: 107 t
char s3[] = abcdef;
108 \0
Example 1: Example 2:
int i=1, j=2, k=3; char *pc[3]={ABC, DEF, GH};
int *pi[3] = {&i, &j, &k};
Variable Address Value
constant 90 A
Variable Address Value constant 91 B
constant 92 C
i 80 1 constant 93 \0
constant Const 94 D
j 82 2 constant 95 E
constant can not 96 F
k 84 3 constant be 97 \0
constant changed 98 G
pi[0] 100 80 constant 99 H
Constant 100 \0
pi[1] 101 82 pc[0] 200 90
pc[1] 202 94
pi[2] 102 84 pc[2] 204 98
Dale Roberts
Command-Line Arguments
argc and argv
In environments those support C, there is a way to pass command-
line arguments or parameters to a program when it begin executing.
When main is called to begin execution, it is called with two
arguments argc and argv
argc : The first (conventionally called argc) is the number of command-
line arguments the program was invoked with
argv : The second (conventionally called argv) is a pointer to an array
of character strings that contain the arguments, one per string.
Example:
if echo is a program and executed on phoenix prompt, such as
10 <phoenix:/home/droberts> echo hello world
argv pointer array
e c h o \0
argc h e l l o \0
3
null w o r l d \0
Dale Roberts
Command-Line Arguments
Example: print out the arguments. ex: hello world
main (int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
printf(%s%c, argv[i], (i < argc-1) ? : \n);
}
Dale Roberts