I am having a problem when using a switch statement to check for something inside an array. I am using an int as my switch, then I compare the character arrays using strstr. So it reads like this:
void function(char *buffer, uint32_t size){
char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
#define TXTCOMPARE1 (char*)"Sample Text 1"
#define TXTCOMPARE2 (char*)"Sample Text 2"
#define TXTCOMPARE3 (char*)"Sample Text 3"
switch(intCompare){
case COMPARE1 :
p = strstr(buffer,TXTCOMPARE1); break;
case COMPARE2 :
p = strstr(buffer,TXTCOMPARE2); break;
case COMPARE3 :
p = strstr(buffer,TXTCOMPARE3); break;
}
if(p!=NULL) { Serial.println("Success!"); }
else { Serial.println("No match"); }
memset(&p,0,sizeof(p);
}
This method does not work and p is always NULL. However, when I write it out without the switch() it compares just fine:
//using the same p declaration as above
p = strstr(buffer,TXTCOMPARE1);
if(p != NULL) { Serial.print("Success:"); }
else { Serial.print("No Match"); }
Why would the switch statement give me different results for what is basically the same function call?
Edit: Actually it seems to break everywhere when I set more than one call to p = strstr(...). When there is only one strstr it works, when two or more are used, it does not...
COMPARE1,COMPARE2andCOMPARE3? Where is your value assigning statement forintCompare?intCompareis being passed intofunction(char *buffer, uint32_t size, int intCompare). But when I have multiple cases, p is alwaysNULLmalloc()intop, and then overwritingpbefore doing afree()? That is not whatstrstr()needs to work. 2) Why do theTXTCOMPAREstrings have(char *)before them? This shouldn't be necessary. 3) Why are you doing amemset(&p,0,sizeof(p));? This is an extraordinarily long-winded way of sayingp = NULL;- and thenpgoes out of scope anyway...char*. Is there a better way to do this? 3)I thought I was trying to clear the p pointer.