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
,COMPARE2
andCOMPARE3
? Where is your value assigning statement forintCompare
?intCompare
is being passed intofunction(char *buffer, uint32_t size, int intCompare)
. But when I have multiple cases, p is alwaysNULL
malloc()
intop
, and then overwritingp
before doing afree()
? That is not whatstrstr()
needs to work. 2) Why do theTXTCOMPARE
strings 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 thenp
goes out of scope anyway...char*
. Is there a better way to do this? 3)I thought I was trying to clear the p pointer.