Reputation: 21
I'm new to C and I'm having some troubles with pointers.
In one function (used to print the words) I have a parameter const char *description
, which is pointing to a string or char array like "There is a faint outline of a face visible".
In another function I'm going to have a pointer which points to the first character in the description
, then move along until it finds a non-space.
char *pointerToFindFirstChar(char *description){
/* Get my pointer to point to first char in description*/
while (*pointerToFindFirstChar == ' ');
pointerToFindFirstChar++;
return pointer
}
I am unsure how I can do that though. what I'm trying to achieve is to find the first non space character in a string which is being pointed at by description and store that in another pointer.(hope that makes sense)
Upvotes: 2
Views: 216
Reputation: 15057
You are currently looking for any different character in your char array. That can also be an exclamation mark or a colon.
Wouldn't it be better to use something like isalnum()
or isalpha()
?
If you are looking for a Digit (0-9) or Alpha-char (a-z or A-Z) then use isalnum else use isalpha.
char * pointerToFindFirstChar(char * description)
{
while(*description && !isalnum(*description))
description++;
return description;
}
or
char * pointerToFindFirstChar(char * description)
{
while(*description && !isalpha(*description))
description++;
return description;
}
It'll add some overhead though. Also, checking for the end of the char array would be required in this case.
An other option would be is to use isspace()
this will check for any white-space character.
See here for these function descriptions: http://www.java2s.com/Code/C/ctype.h/Catalogctype.h.htm
Upvotes: 0
Reputation: 5183
Just for the record, it is possible to have the post-increment directly in the condition of the loop:
char *pointerToFindFirstChar(char *description)
{
while (*description++ == ' ');
return description;
}
In this case you do have an empty loop body because the increment is performed right after the evaluation of the pointer inside the loop condition.
Upvotes: 0
Reputation: 23266
char *find_first_char(char *desc)
{
while (*desc == ' ') desc++;
return desc;
}
Upvotes: 1
Reputation: 17535
Try this:
char *pointerToFindFirstChar(char *description)
{
while(*description == ' ')
description++;
return description;
}
Note that checking for the null byte at the end of the string is unnecessary, as when *pointer == '\0'
, the condition on the while loop while be false and the loop will end anyway.
Getting rid of the ;
at the end of the while
line is important; otherwise, the loop will have no body and either run 0 times or infinitely (since pointer
would never be changed in the loop). If it ran 0 times, then the increment would happen after exiting the loop.
Upvotes: 1