Skip to main content
Ala
Senior
September 28, 2020
Solved

indexing a array

  • September 28, 2020
  • 2 replies
  • 1160 views

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.
    Best answer by Tesla DeLorean

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

    2 replies

    Ozone
    Principal
    September 28, 2020

    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
    September 28, 2020

    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
    September 28, 2020

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

    Tips, Buy me a coffee, or three.. PayPal VenmoUp vote any posts that you find helpful, it shows what's working..
    Ala
    AlaAuthor
    Senior
    September 29, 2020

    dear clive1

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