cancel
Showing results for 
Search instead for 
Did you mean: 

indexing a array

Ala
Senior

hi

I want to locate a string in an other string and then mark its position with an 'X'. here is the code

#include "main.h"
#include "adc.h"
#include "dma.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"
#include "stm32f1xx.h"
#include <string.h>         
#include <stdio.h>          
#include <stdlib.h>
 
int position;
char  Rcv[500];
char  *ret;

ret=strstr(Rcv,"+CMTI");
position=ret-Rcv;	
Rcv[position]='X';

the code doesn't run. when I comment the third line, it works. why is that?

1 ACCEPTED SOLUTION

Accepted Solutions

  1. ret=strstr(Rcv,"+CMTI");
  2. if (ret) Rcv[(int)(ret-&Rcv[0])]='X';

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

View solution in original post

4 REPLIES 4
Ozone
Lead

The POSIX function strstr() already returns the first position of the substring, I see no need for your pointer fiddling.

The returned pointer can be NULL.

That is simple C stuff, which can easily be tested on the host.

The clib implementation of you embedded project might have limited POSIX compatibility.

Ala
Senior

dear Ozone

  1. but when I monitor ret, it is '+' and not the position of '+' in Rcv. also, more importantly, when I am running the above code, ret is not evaluated but just as I comment the third line, it is evaluated and I get the position number right. I don't understand!!! isn't it supposed to work line by line? so why removing third line affects first and second line(ret=strstr(Rcv,"+CMTI"; & position=ret-Rcv;)???
  2. what do you mean my implementation is not OSIX compatible? can you help me with some example for this type of situation?

)

  1. ret=strstr(Rcv,"+CMTI");
  2. if (ret) Rcv[(int)(ret-&Rcv[0])]='X';

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

dear clive1

it worked! you are amazing as always!🙏