I am reading the book:
The C Programming Language 2nd Edition
By: Brian W. Kernighan and Dennis M. Ritchie
Right now I am revising pointers although till now I haven't used malloc, calloc and alloc.
I will post some of my worked examples for comments as I know feedback is very important where learning is involved.
Since I find myself noticeably weak where pointer use is involved, I think, it is better to start with pointers.
Code: Select all
#include <stdio.h>
#include <ctype.h>
/* assume target string has enough free space */
void strcat1(char* s, char *t) {
/* find terminating null */
/*
The for loop increments pointer t after every iteration.
Loop starts at t. The final value of t is the position of
/0 character.
*/
for (; *t; t++);
/*
The while loop uses C's bastardized version of an assignment
treating it also as a statement. At each iteration, first the
char at t is assigned the char at s. After this, both t and s
are incremented.
*t++ means first increment the pointer, then dereference it,
otherwise this wouldn't work.
*/
while(*t++ = *s++);
}
int main() {
/*
Here I am assuming both source and target are automatically
appended by a \0 character. Otherwise strcat1 would go into
an uncontrolled memory corrupting frenzy only to be stopped
by a segmentation fault.
However this didn't happen.
*/
char source[] = "Appended end of string\n";
char target[1024] = "Target string\n";
strcat1(source, target);
printf(target);
return 0;
}
Code: Select all
#include <stdio.h>
#include <ctype.h>
int strend(char* s, char* t) {
char* saved_t = t;
for (; *t; t++);
for (; *s; s++);
while (*--t == *--s);
return (t + 1 == saved_t);
}
int main() {
char a[] = "mouse, cat, dog\n";
char b[] = "cat, dog\n";
char c[] = "horse, cow\n";
if (strend(a, b))
printf("b found in a\n");
else printf("b not found in a\n");
if (strend(a, c))
printf("c found in a\n");
else printf("c not found in a\n");
return 0;
}