View previous topic :: View next topic |
Author |
Message |
Jerry I
Joined: 14 Sep 2003 Posts: 96 Location: Toronto, Ontario, Canada
|
Question about strchr() function |
Posted: Tue Sep 13, 2016 6:26 pm |
|
|
I ported some old code from an older version of CCS compiler Version 4.140
Code: |
char tmpbuf[20];
strcpy(tmpbuf, ".1234");
ptr = strchr(tmpbuf, '.');
|
CCS Version 4.140 -> ptr = 0
CCS Version 5.042 -> ptr = 1
I checked both string.h files from both versions of the compiler, the function is the same.
Which is correct ?.
I thought ptr = 0 is correct because the '.' is in the tmpbuf[0] position.
Thanks for help |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Tue Sep 13, 2016 7:04 pm |
|
|
It doesn't return the array index of the character. It returns a pointer to
RAM memory. Depending upon where the compiler placed the buffer
in RAM, the returned pointer could be anything.
Example:
In the program below, if I compile and then run it in MPLAB vs. 8.92
simulator, it displays this output in the UART1 output window:
To see what address 0007 is, let's look at RAM addresses in the .SYM file:
Code: | 000 @SCRATCH
001 @SCRATCH
001 _RETURN_
002 @SCRATCH
003 @SCRATCH
004 rs232_errors
005-006 strtok.save
007-01A main.tmpbuf <== 0007 is the start of tmpbuf
01B-01C main.ptr
etc.
|
So the address returned (0007) is the first byte in the array.
It's at array index 0. This is the correct result.
Test program:
Code: | #include <18F4620.h>
#fuses INTRC_IO,NOWDT,PUT,BROWNOUT,NOLVP
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
#include <string.h>
//======================================
void main(void)
{
char tmpbuf[20];
char *ptr;
strcpy(tmpbuf, ".1234");
ptr = strchr(tmpbuf, '.');
printf("ptr = %lx \r", ptr);
while(TRUE);
} |
|
|
|
Jerry I
Joined: 14 Sep 2003 Posts: 96 Location: Toronto, Ontario, Canada
|
|
Posted: Tue Sep 13, 2016 8:54 pm |
|
|
I understand now. Thanks
Is there any easy way to get the position (index number) of the search character in the string.
I know I can use a for loop and do a compare and count, but wanted something better.
Thanks again.
Jerry |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19537
|
|
Posted: Wed Sep 14, 2016 12:51 am |
|
|
Just subtract....
ptr = strchr(tmpbuf, '.')-tmpbuf;
strchr returns the address in memory. tmpbuf (or any other array name), is the address in memory of the first byte of the array. Location-start = position in string. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Sep 14, 2016 8:46 am |
|
|
You should check for a NULL ptr result from strchr() before you
do the subtraction. If you got a NULL, then don't use it.
Or you could make a function, and if you got the index then return it.
If you got a NULL pointer, then return False. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19537
|
|
Posted: Wed Sep 14, 2016 8:51 am |
|
|
Very true.
For a simple print, doesn't matter, but for a 'real' program, important. |
|
|
|