Reputation: 3
In this code I have a function besides main which finds a specific character in a string (sentence) and returns a pointer to it and otherwise it returns NULL:
char *position (char letter, char *sentence){
int i=0;
while (*(sentence+i) != '\0') {
if (toupper(*(sentence+i)) == toupper (letter))
return (sentence+i);
++i;
}
return NULL;}
It's all clear to me here.
And in the main function i have to use the previous function (position) to find how many times does a specific letter appear in a specific sentence.
int main (void){
char sentence [200+1];
char letter;
char *pos = sentence;
int counter=0;
gets(sentence);
scanf("%c", &letter);
while (pos != NULL){
pos = position (letter, pos);
if (pos != NULL){
++counter;
pos +=1;
}
}
return 0;
}
What is unclear to me is what is exactly in the pos variable once it is set and how exactly the while loop at the end works?
edit: forgot to initialise variable i
in function()
, thanks for pointing it out
Upvotes: 0
Views: 93
Reputation: 146
Lets do a small example: you've got the String "abaab" and your looking for the Letter b. As you know a C-String always ends with '\0'. So at beginning your pos represents the whole string.
abaab\0 //pos represents ="abaab"
|
pos
After that you call your function: postiton(pos, 'b'). Pos now points on the seccond letter. And with this pos only represents the smaller String "baab".
abaab\0 //pos represents="baab"
|
pos
After ++pos; you got this situation: (pos represents a smaller String)
abaab\0 //pos represents ="aab"
|
pos
When you now call the position function again. pos will point on the next 'b'. And of course the String is shorter again.
abaab\0 //pos represents ="b"
|
pos
Increment pos:
abaab\0 //pos represents =""
|
pos
Calling the position function again will return NULL, because there is no 'b'. When this function returns NULL the while function is finished.
Upvotes: 2
Reputation: 23711
What is unclear to me is what is exactly in the pos variable once it is set and how exactly the while loop at the end works?
Your code contains lot of bugs but if your question is just what I quote a simple answer is:
pos
is a pointer in sentence
string. Start to point in where sentence
point and move away to reach the end of string.
position()
take a start point end return the point where letter
is found, otherwise it return NULL
: so when you write pos = position (letter, pos);
pos
is moved to letter
position. After that by pos +=1;
you move away to the next element (move the pointer of one char).
When there are any letter position()
return NULL
and while
cycle terminate.
Upvotes: 1
Reputation: 16017
pos is initialized with char *pos = sentence;
which lets it point to the first character in sentence
, due to arrays "decaying" to pointers in most expressions, like this one. After that, it points to elements inside sentence
because position()
returns sentence+i
which is the address of the first element of sentence plus the offset i.
Upvotes: 0