Beruflich Dokumente
Kultur Dokumente
Julian Gough
Outline
1 Problem
2 Strings
Characters
Strings
3 ProblemInput
4 Arrays of Pointers
Pointer Arithmetic, Recap
5 ProblemOutput
Problem
Problem
Write a program that reverses short sentences
Outline
1 Problem
2 Strings
Characters
Strings
3 ProblemInput
4 Arrays of Pointers
Pointer Arithmetic, Recap
5 ProblemOutput
Strings Characters
Characters in C
Characters in C
Characters in C
Input/output
Using printf and scanf
The conversion specifier %c is used for char
char ch;
scanf("%c", &ch);
printf("%c", ch);
Strings in C
Strings are specially terminated arrays of char
An array of characters is known as a string.
Strings in C
Input/output
char blurb[20];
scanf("%19s", blurb); Pra meter slo 19 caracteres
printf("%s", blurb);
Strings Strings
Strings in C
Input/output
char blurb[20];
scanf("%19s", blurb);
printf("%s", blurb);
Safety first!
You need to specify the length of the blurb beforehand! Serious risk of
buer overflows without...
scanf("%s", blurb);
Strings Strings
Strings in C
Input/output
char blurb[20];
scanf("%19s", blurb);
printf("%s", blurb);
Attention on ampersands!
Correct: scanf("%19s", blurb);
Wrong: scanf("%19s", &blurb);
(Visual Studio allows bothwe dont!)
Strings Strings
Strings in C
Input/output
char blurb[20];
scanf("%19s", blurb);
printf("%s", blurb);
Strings in C
Input/output
char blurb[20];
scanf("%19s", blurb);
printf("%s", blurb);
Using fgets
fgets(blurb, sizeof(blurb), stdin);
This is always safe to read an entire line
It the input is too long, part of it is left unread;
If it fits, blurb will also contains the enter
We will see the meaning of stdin next week.
Strings Strings
Strings in C
Input/output
Strings in C
The <strings.h> library
Pointer Arithmetic
Plus the link with arrays
for (i=0, aPtr=a; ((i < 6) && (*aPtr > 2)); i++, aPtr++) }
*aPtr += 10; // add 10 to content of this address
}
Pointers revisited
aPtr++ causes the pointer to advance
As a result, *aPtr == a[i]
In fact, a[i] is simply shorthand for *(a+i)
ProblemInput
Outline
1 Problem
2 Strings
Characters
Strings
3 ProblemInput
4 Arrays of Pointers
Pointer Arithmetic, Recap
5 ProblemOutput
Arrays of Pointers
Outline
1 Problem
2 Strings
Characters
Strings
3 ProblemInput
4 Arrays of Pointers
Pointer Arithmetic, Recap
5 ProblemOutput
Arrays of Pointers Pointer Arithmetic, Recap
Outline
1 Problem
2 Strings
Characters
Strings
3 ProblemInput
4 Arrays of Pointers
Pointer Arithmetic, Recap
5 ProblemOutput