Ćwiczenia
Poniższe ćwiczenia mają za główne zadanie zatrzymać się nad bardzo prostym (na ogół) kodem i dokładnie zastanowić się co robią poszczególne instrukcje, oraz próbować odgadnąć co robi cały program (lub całą funkcja).
Ćwiczenie 1
[c]
int p1(char str[])
{
int i = 0;
while (str[i] != '\0′)
{
i++;
}
return i;
}
[/c]
Ćwiczenie 2
[c]
int p2(char* str)
{
int i = 0;
while (*str != '\0′)
{
i++;
str++;
}
return i;
}
[/c]
Ćwiczenie 3
[c]
void p3(char dest[], char src[])
{
int i = 0;
while (src[i] != '\0′)
{
dest[i] = src[i];
i++;
}
dest[i] = '\0′
}
[/c]
Ćwiczenie 4
[c]
void p4(char dest[], char src[])
{
int i = 0;
while (( dest[i] = src[i] ) != '\0′)
{
i++;
}
}
[/c]
Ćwiczenie 5
[c]
void p5(char* dest, char* src)
{
while (( *dest = *src ) != '\0′)
{
dest++;
src++;
}
}
[/c]
Ćwiczenie 6
[c]
void p6(char* dest, char* src)
{
while (( *dest++ = *src++ ) != '\0′);
}
[/c]
Ćwiczenie 7
W tym ćwiczeniu szczególnie należy zwrócić uwagę na linię 13. Jaki jest jej sens? Co ona oznacza?
[c linenumbers=”inline”]
#include
#include
int findA(char[]);
int main(int argc, char* argv[]){
char oldString[] = {’H’, 'e’, 'l’, 'l’, 'o’, '\n’};
printf(„Calling findNull, will seg fault now\n”);
findA(oldString);
printf(„Program complete\n”);
return EXIT_SUCCESS;
}
int findA(char newArray[]){
int i = 0;
while(newArray[i] != 'A’ || newArray[i + 1] != 'A’) {
i++;
}
printf(„Found at: %d\n”, i);
return i;
}
[/c]
Ćwiczenie 8
Ten program jest źle zaprogramowany. Na czym to „złe zaprogramowanie” polega?
[c]
#include
#include
#define SIZE 1000000000
#define TRUE 1
int main() {
int j;
int *data;
int numMallocs = 0;
while (TRUE) {
data = (int*)malloc(SIZE * sizeof( int ));
if (data == NULL) {
printf(„memory allocation error: data\n”);
return EXIT_FAILURE;
}
printf(„%d\n”, ++numMallocs);
for (j = 0; j < SIZE; j++) {
data[j] = j;
}
}
free(data);
return EXIT_SUCCESS;
}
[/c]
Ćwiczenie 9
[c]
int p9(char *s, char *t)
{
int Result = 0;
int s_length = 0;
int t_length = 0;
s_length = strlen(s);
t_length = strlen(t);
if(t_length <= s_length)
{
s += s_length - t_length;
if(0 == strcmp(s, t))
{
Result = 1;
}
}
return Result;
}
[/c]
Ćwiczenie 10
Zaproponować sposób użycia.
[c]
double p10(int n, double x, double a[])
{
double r = 0;
int i;
for (i = n; i >= 0; i–)
r = r * x + a[i];
return r;
}
[/c]
Ćwiczenie 11
[c]
#include
main()
{
char *text_pointer = „Good morning!”;
for(; *text_pointer != '\0′; ++text_pointer)
printf(„%c”, *text_pointer);
}
[/c]
Ćwiczenie 12
[c]
#include
main()
{
static char *days[] = {
„Sunday”, „Monday”, „Tuesday”, „Wednesday”, \
„Thursday”, „Friday”, „Saturday”
};
int i;
for ( i = 0; i < 6; ++i )
printf( "%s\n", days[i]);
}
[/c]
O zmiennej typu static
można poczytać w rozdziale [static].