2016-10-30 1 views
1

이 for 루프를 통해 포인터를 전달하려고하지만 작동하지 않습니다. 이것은 원래 코드의 블록입니다. 나는 200 줄의 코드로 당신에게 모든 것을 과부하하고 싶지 않았다! 이 모든 것이 필요하면 부탁하십시오.for 루프 및 if 문을 통해 포인터 전달

그래서 3 개의 printf를 사용하여 코드가 충돌하기 전에 얼마나 멀리 떨어져 있는지 보았습니다. 그것은 printf ("2")에 도착합니다; 추락하기 전에. 그래서 나는 그것이 무언가라고 가정하고 있습니다. if (*(userInput + i) == sNumArray[j]) 제가 잘못하고있는 것이 확실하지 않습니다. 내가 아는 한 포인터는 포인터 [i]를 사용하여 각 요소를 순환한다. *(pointer + i)?

나는 4 주 전에 프로그래밍을 시작 했으므로 이것을 철저히 설명하지 않으면 미안합니다. 난 아직도 용어 등

for (i = 0; i < sUserInput_SIZE; i++) { 

    printf("1"); 

    for (j = 0; j < sNumArray_SIZE; j++) { 

     printf("2"); 

     if (*(userInput + i) == sNumArray[j]) { 

      validInput++; 
      printf("3"); 

     }//End if() 

    }//End inner for() 

}//End outer for() 

을 배우고 여기에 내 소스 코드 내가 무엇을 사용자가 입력하는 숫자인지 아닌지 확인하는 함수를 작성하는 것을 시도하고있다. 주요 코드는 사용자가 핀을 입력하고 핀을 변경하며 핀이 올바르게 입력 된 횟수를 볼 수있는 atm입니다.

isdigit 함수로 오류를 검사 할 수 있지만 학습을 위해 내 자신의 함수를 만들어보고 싶었습니다. 그리고 이것에 많은 시간을 할애했으며, 무언가를 시도하도록 고집합니다. 그밖에.

#include <stdio.h> 
#include <string.h> 

#define sUserInput_SIZE 5 
#define sNumArray_SIZE 10 


char * errorChecking(char *userInput) { 

    //VARIABLE LIST 
    //Note: Each variable will have the alphabetical character associated with its data structure at the beginning of its name e.g. integer data structures will have the charater "i" at the beginning of the variable etc 
    //Outer for loop variable 
    unsigned i; 
    //Inner for loop variable 
    unsigned j; 
    // validInput will be compared with strlen() function which is an unsigned int........more? 
    unsigned iValidInput = 0; 

    //ARRAY LIST 

    //This array will be used to check each inputed character to check if it is a number 
    char sNumArray[sNumArray_SIZE] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 

    //End of Declarations 


    //This for loop will cross reference each element the user inputed with the number array 
    for (i = 0; i < sUserInput_SIZE; i++) { 

     for(j = 0; j < sNumArray_SIZE; j++) { 

      if (*(userInput + i) == sNumArray[j]) { 

       //Every time a number is successfully verified as a number the "validInput" variable will be incremented by 1 
       iValidInput++; 

      }//End if() 

     }//End inner for() 

    }//End outer for() 


    //This if statement will check if the inputed value is an integer or not by checking if the number of valid inputs equalls the length of the sUserInput array 
    if (validInput == strlen(userInput)){ 

     printf("\n\nIs a integer"); 
     return(userInput) 

    }//End if() 
    else { 
     printf("\n\nIs "); 
     printf("\n\nError: This is not a integer \nTry again: "); 
     scanf("%s" , &userInput); 


    }//End else 



    return(userInput); 

}//End main() 

//FIX ME: only add convert it input is verified 
//FIX ME: Loop back around if it is not a number 

int main() { 

    //VARIABLE LIST 
    //Note: Each variable will have the alphabetical character associated with its data structure at the beginning of its name e.g. integer data structures will have the charater "i" at the beginning of the variable etc 

    int iExitLoop = 1; 
    unsigned int iCorrectInputs = 0; 
    unsigned int iIncorrectInputs = 0; 
    char *iNewUserPin = "0"; 
    char *iUserPin = "1234"; 
    char *sUserInput = "1"; 


    //End of Declarations 


    while (iExitLoop == 1) { 

     //Main menu 
     printf("\n1: Enter pin"); 
     printf("\n2: Change pin"); 
     printf("\n3: Successful and unsuccessful pin logs"); 
     printf("\n4: Exit"); 
     printf("\n\n%s" , sUserInput); 

     //Prompting the user to entered in an option 
     printf("\n\nEnter: "); 
     scanf("%s" , &sUserInput); 
     printf("%s" , *sUserInput); 

     //Prompting user to enter pin 
     if (strncmp(sUserInput , "1" , 1) != 0) { 

      //This do while loop will prompt the user to enter in their pin and keep running until the correct pin is entered 
      do { 
       printf("\nPlease enter your pin: "); 
       scanf("%s" , &sUserInput); 
       errorChecking(sUserInput); 

       if (sUserInput == iUserPin) { 
        iCorrectInputs++; 
       }//End if() 
       else { 
        iIncorrectInputs++; 
        printf("\nTry again!"); 
       }//End else 
      } while (sUserInput != iUserPin);//End Do While() 
      //FIX ME - ADD ERROR CHECKING (FUNCTIONS?) 

     }//End if() 


     //Prompting user to change their pin 
     if (sUserInput == "2") { 

      do { 
       printf("\nPlease enter you current pin: "); 
       scanf("%s" , &sUserInput); 
       //FIX ME - ADD ERROR CHECKING (FUNCTIONS?) 

       if (sUserInput != iUserPin) { 
        printf("\nIncorrect pin!"); 
       }//End if() 

      } while (sUserInput != iUserPin);//End do while() 


      while (iNewUserPin != iUserPin) { 

       printf("\nEnter new pin: "); 
       scanf("%s" , &iNewUserPin); 

       printf("Re-enter new pin: "); 
       scanf("%s" , &iUserPin); 

       if (iNewUserPin != iUserPin) { 

        printf("\nTry again!"); 

       }//End if() 

      }//End while() 

     }//End if() 


     //This block of code will the display the amount of correct and incorrect inputs 
     if (sUserInput == "3") { 

      printf("\nYour pin was correctly entered %d times" , iCorrectInputs); 
      printf("\nYour pin was incorrectly entered %d times" , iIncorrectInputs); 

     }//End if() 

     //This block of code will end the program if the user inputs 4 
     //FIX ME: possibly use sUserInput for loop execution 
     if (sUserInput == "4") { 

      iExitLoop = 0; 

     }//End if() 

    }//End while() 

    return(0); 

}//End main() 


//FIX ME: error checking for 4 character input 
+1

출력 버퍼를 플러시하지 않았기 때문에 출력에 결함이 있습니다. 즉, 많은 출력을 버퍼링 할 수 있고 충돌은 생각하는 곳과 관련이없는 다른 곳에서 발생합니다. 'printf' 문자열은 항상 버퍼를 플러시하는 개행 (' "\ n"')으로 끝내십시오. –

+1

그리고 디버거 사용법도 배워야합니다. 디버거에서 프로그램을 실행하면 충돌이 발생했을 때 프로그램이 멈추고 위치가 표시됩니다. 코드에 크래시가 없으면 코드를 찾을 때까지 호출 스택을 올릴 수 있습니다. 그런 다음 변수를 검사하고 그 값을 볼 수 있습니다. –

+0

'pointer [i]'와 같이 접근하는 것에 대한 혼란에 대해. 이것은 포인터뿐만 아니라 배열에도 모두 맞습니다. '[]'첨자 연산자는 배열뿐만 아니라 포인터에도 사용될 수 있습니다. – ameyCU

답변

3

게시 한 코드 조각에 본질적으로 문제가 없습니다. 실제로 *(userInput + i)은 정확히 userInput[i]과 같습니다. 배열 크기에 일관성 문제가있을 수 있습니다.

userInputsUserInput_SIZE을 사용한다는 점에 유의하십시오. 이름이 일치하지 않습니다. 2 개의 다른 배열 userInputsUserInput이있을 수 있으며 크기가 다를 수 있습니다.

편집 : 전체 소스 코드에서

, sUserInput는 1 문자열 "i"에 대한 포인터가 나타납니다. 이 포인터에서 오프셋 1을 초과하는 바이트에 액세스하면 정의되지 않은 동작이 호출됩니다.

for (i = 0; userInput[i] != '\0'; i++) { 
    for (j = 0; j < sNumArray_SIZE; j++) { 
     if (userInput[i] == sNumArray[j]) { 
      validInput++; 
     } 
    } 
} 

당신은 userInput 최초의 길이를 계산할 수 있고 루프의 상한으로 길이를 사용하는 대신 sUserInut_SIZE 때까지 반복으로, 문자열을 처리하고 있기 때문에, 당신은 단지 null 종결을 테스트한다 값을 비교하여 최종 validInput을 비교합니다.

코드의 나머지 부분에서 더 많은 문제가 있습니다

  • 하여 오류 처리 코드 유효성에 대한 두 번째 항목을 확인하지 않습니다.

  • 더 중요 : scanf()sUserInputmain()에서 읽는 것이 잘못되었습니다.당신이 strncmp()의 반환 값으로 == 0을 확인해야합니다,

    char sUserInput[20]; 
    
    if (scanf("%19s", sUserInput) == 1) { 
        /* handle sUserInput */ 
    } else { 
        /* premature end of file? */ 
    } 
    
  • 귀하의 비교 if (strncmp(sUserInput , "1" , 1) != 0)가 부정확하고 strcmp()는 (하위) 문자열이 동일한 것이 0입니다 : 당신은 사용해야합니다.

  • 당신은 ==와 문자열을 비교할 수 없습니다 : if (sUserInput == "2")은 마찬가지로, if (sUserInput == iUserPin)이 잘못 if (strcmp(sUserInput, "2") == 0)

  • 로 변경해야합니다. 이 경우에도 strcmp()을 사용하십시오.

+0

userInput은 함수 인수이고 sUserInput_SIZE는 #define 크기입니다. 전체 코드를 게시했습니다. 그냥 "FIX ME :"주석을 무시하십시오. –

+0

@ C.Centre : 업데이트 된 답변보기 – chqrlie