Skip to main content
Ala
Senior
Sep 28, 2020 1:09 PM UTC
Solved

indexing a array

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?

    This topic has been closed for replies.
    Tesla DeLorean
    Tesla DeLoreanBest answer
    Guru
    Sep 28, 2020 8:48 PM UTC

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

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

    4 replies

    Ozone
    Principal
    Sep 28, 2020 2:07 PM UTC

    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
    AlaAuthor
    Senior
    Sep 28, 2020 8:42 PM UTC

    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?

    )

    Tesla DeLorean
    Tesla DeLoreanBest answer
    Guru
    Sep 28, 2020 8:48 PM UTC

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

    Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..
    Ala
    AlaAuthor
    Senior
    Sep 29, 2020 5:13 AM UTC

    dear clive1

    it worked! you are amazing as always!:folded_hands: