Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

a simple question on string operation

Status
Not open for further replies.

erxuan

Programmer
Feb 7, 2003
3
US
when I implement the function
char *strchr( const char *string, int c );
I got a problem. If I wrote like this:


char *my_strchr(const char *string, int c)
{
while(*string && *string!=c){
string++;
}

return string;
}


I was told the string is const char*, and the return value is char*, can not return directly.

If I use new a char pointer, I also can not use assign operator directly since char * = const char* is wrong. What should I do in this situation?

Thanks.
 
Wouldn't assigning a pointer to *string work for you?

char *my_strchr(const char *string, int c)
{

char *pstr = string;

while(*pstr && *pstr != c){
pstr++;
}

return pstr;
}
 
No, it doesn't work. When I compile it, it will say "cannot transfer const char * to char *" when it met
char *pstr = string;
 
I get warnings but gcc allows me to do it.
Hmm...
Well, I guess you will have to modify the
function args to straight char * and copy
the const char* string to another.
That's all I can think of.

Code:
int main(void) {
char *pstr, *new;

      pstr = malloc(strlen(line) * sizeof(char));
      strcpy(pstr,line);
      printf("%s\n", pstr);
      new = my_strchr(pstr,'l');
      printf("%s\n", new);

return 0;
}


char *my_strchr(char *string, int c) {

    while(*string && *string!=c){
        string++;
    }
    
    return string;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top