sure...
Code:
int count_char(char* str, char needle)
Since we're counting chars we ned to be able to call the function with a string (char array) and the char to look for
We need to keep track of how many we've found during the count, thus the integer here, if tehres none, it's allready set at 0, since this is strict ANSI C, we need to declare the variabel befor anything else is done in teh function.
For as long as the string has something besides NULL in it, we should do stuff.
Code:
if(*str == needle)
count++;
if our current location in the string equals the char we're looking for, increment the counter to reflect our current count.
Shift our current location in teh string one storage size to the right, or left, or up, or down, depending on how you like to see it
when we exit from teh while loop, we return with our pressent count.
When dealing with strings or char arrays, ther memory usage is actualy consisting of one part beeing the value stored at the possition in teh string aswell as the memory location teh string is occupying.
The
*str == needle compares the value stored at current memory location with needle.
The
str++ increments the memory value, thus moving us one place further into the memory occupied by teh string, thus possitioning us at the next char in teh string.
Sorry, thats just about the easiest way I can explain it, without draving it up in hand..
Anyway here it is drawn:
Code:
Memory representation of:
char str[] = "string"
.---.---.---.---.---.---.----.
Index: | 0 | 1 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|----|
Char: |'s'|'t'|'r'|'i'|'n'|'g'|'\0'|
'---'---'---'---'---'---'----'
mem point: ^
'
After str++;
.---.---.---.---.---.---.----.
Index: | 0 | 1 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|----|
Char: |'s'|'t'|'r'|'i'|'n'|'g'|'\0'|
'---'---'---'---'---'---'----'
mem point: ^
' So when you use str[i] you're refering to the index line in the memory, when you address *str you're addressing the char line in the memory, when you use str++, instead of changing the index and looking at the char section from that line, you change the mem point, and see it from that side.
Now the limitation of my ascii skills, prevents me from adding the pointer to next item handling in case 's' is located at memory location
0xff2341de and 't' is located at memory location
0xfff2132d but any compiler logic book, like the dragon book, will tell you all about how this is handlet.. Actualy the thing teh str++ changes is infact the
mem pointer shift
next item pointer but as I said any compiler designs book will elaborate this to the fullest.