简体   繁体   中英

Finding all the possible IP addresses, running into infinite loop

This is a problem where you have to enter a number having non zero digits and the program will convert it into a IP address having 4 parts and each part less than 255, and have to print all the IP addresses.
I have tried this recursive method and am running into an infinite loop.

#include<stdio.h>
#include<math.h>
int a[3];
void comuni(unsigned long n,int count){
    int i=count;
    do{
        if(count<0){
            return;
        }
        int t=pow(10,i);
        a[count]=n/t;
        int rem=n%t;
        if(a[count]<=255 &&a[count]>0 && count>=0){
            printf("%d.",a[count]);
            comuni(rem,count-1);
        }    
        i++;
    }while(1);
}

int main()
{
    //  Insert your code here.
    unsigned long n;
    scanf("%ul",&n);
    comuni(n,3);
    return 0;
}

Your question is why there is an infinite loop.

Starting with a look at while(1) it does not surprise me.
But wait, there is a return inside, which is used if count is less than 0.
Nothing inside the loop changes count . So if count is greater or equal 0 to begin with you got your infinite loop.

I think the problem which causes that situation is that this

int i=count;

does NOT cause count to change when you change i .
You do change i inside the loop, but you know - it does not help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM