strchr

General discussion on mikroC PRO for PIC.
Post Reply
Author
Message
HyperUniverse
Posts: 282
Joined: 17 Jun 2009 10:42

strchr

#1 Post by HyperUniverse » 06 Oct 2022 21:07

why is my strchr returning the decimal value of the character, rather than its position number in the string?

Code: Select all

SubString = "100150C4304E2512" ;
res = strchr(SubString, 'C');

res =  67
why don't I get res = 7?

hexreader
Posts: 1786
Joined: 27 Jun 2010 12:07
Location: England

Re: strchr

#2 Post by hexreader » 07 Oct 2022 10:31

I think that you are stuck in a BASIC mind-set

You need to adjust to a C mind-set

for instance, this is not valid C:

Code: Select all

SubString = "100150C4304E2512" ;
res needs to be a pointer, not a byte

res will give the memory address where it found 'C', not it's position in the string the way BASIC does

Here is my attempt at getting string position, but I suspect that using pointers may often be better than string position

Code: Select all

// random code for forum     Author will deny all responsibility for this terrible code
// do not do this!!!   this is a BASIC mind set, and silly for C

char SubString[] = "100150C4304E2512" ;
char *res;                                   // pointer for memory address

void main() {

    TRISB = 0;                               // all output for LEDs
    LATB = 0;                                // initialise
    
    res = strchr(SubString, 'C');            // get a memory pointer value into res

    if(res){                                 // only process if non-zero (character found)
        LATB = (res - &SubString) + 1;       // get a BASIC style result - you do not want to do this
    }
    else{
        LATB = 0;                            // character not found
    }
    
    while(1);                                // loop forever to aid debugging
}
Start every day with a smile...... (get it over with) :)

Post Reply

Return to “mikroC PRO for PIC General”