for loop bug ?

:zipper_mouth_face:

|500x215 |500x215

Aside from the useless emoticon, did you have something to say?

i inside

if (i > 3)
 break;

in for loop and result ditto.

Full my code

String SerialGET = "";

void setup() {
Serial.begin(9600);
}

void loop(){
 while (Serial.available()) {
   char c = Serial.read();
   if (c == '\n') {
     /* You code chk */
     Serial.println(SerialGET);
     Serial.println(IPValid(SerialGET));
     SerialGET = "";
   }else
     SerialGET += c;
 }
}

bool IPValid(String IP){
 int DotCount = 0;
 int StartArr[4];
 StartArr[0] = 0;
 for (int i = 0; i < IP.length();) {
   i = IP.indexOf('.', i);
   if (i == -1)
     break;
   i++;
   StartArr[DotCount+1] = i;
   DotCount++;
 }
 if (DotCount != 3)
   return false;
 if ((sizeof(StartArr)/sizeof(int)) - 1 > 3)
   return false;
 StartArr[4] = IP.length()+1;
 bool Error = false;
 for (int i=0;i<4;i++){
   if (i > 3)
     break;
   Serial.println("i: " + String(i));
   String CutS = IP.substring(StartArr[i], StartArr[i+1]);
   if (CutS.length() < 1)
     return false;
 }
 return true;
}
 if ((sizeof(StartArr)/sizeof(int)) - 1 > 3)
   return false;

This is pretty silly. The size of the array is fixed at compile time. Storing, or not, values in the array does not change the size of the array.

 StartArr[4] = IP.length()+1;

Equally silly. The array size is 4, meaning that the index values range from 0 to 3. Writing off the end of the array is NEVER a good idea.

 for (int i=0;i<4;i++){
   if (i > 3)
     break;

More silliness. If you want the loop to iterate fewer times, change the while clause.

this my code problem is loop if. array set and size no problem. :sweat_smile:

 for (int i = 0; i < IP.length();) {
   i = IP.indexOf('.', i);
   if (i == -1)
     break;
   i++;

You have totally lost me there. You have a for loop, and in the middle you are changing the loop index. And after that, well, I have no idea.

int StartArr[4];
  :
 StartArr[4] = IP.length()+1;

There is no StartArr[4]. This probably overwrites some local stack variable, with unpredictable results.

You have a for loop, and in the middle you are changing the loop index.

Sure. Why not.

Hmm. Make it a while loop, perhaps?

You can probably make it work. It’s not good design.