Complete Beginner: проблема с нулевым указателем? - PullRequest
0 голосов
/ 11 февраля 2012

Я просмотрел все форумы, чтобы попытаться понять эту проблему. Причины, по которым я не могу полностью понять проблему и почему я не могу найти решение, заключаются в том, что я довольно новичок в C ++ и не понимаю сообщения об ошибке.

Это мой код на C ++, который находит количество возможностей по перестановке или комбинационным формулам. Каждый раз, когда я пытаюсь скомпилировать и запустить, я получаю сообщения, которые говорят:

Исключение первого шанса на 0x6a8613af (msvcr100d.dll) в Combination_Permutations.exe: 0xC0000005: чтение о нарушении доступа местоположение 0x00000005. Необработанное исключение в 0x6a8613af (msvcr100d.dll) в Combination_Permutations.exe: 0xC0000005: чтение о нарушении доступа местоположение 0x00000005.

На многих других форумах я узнал, что "местоположение чтения нарушения доступа 0x00 ..." может определенно указывать на нулевой указатель. Но я не вижу, где я сталкиваюсь с такой нулевой проблемой. Может быть, к моим переменным обращаются глобально, где они еще не инициализированы? Вот мой код, я был в нем какое-то время ... как я уже говорил, я довольно новый. Поэтому, пожалуйста, сообщите мне о моих ошибках. Спасибо.

Мой код:

    #include <iostream>
#include "conio.h";
using namespace std;

int run_combination(int n, int r);
int run_permutation(int n, int r);
int solve_factorial(int f);

int f_value = 1; //factorial value used recursively
int n_input, r_input;
char choice;
char order;
void main(){
            //if user types choice as 'q', while loop ends
    while(choice != 'q'){
        printf("How many values? (1-9) \n");
        printf("User: ");
        cin >> n_input;//user input for variable n
        printf("n_input: %i", n_input);

        printf("\nHow many will be chosen at a time out of those values? (1-9)\n");
        printf("User: ");
        cin >> r_input; //user input for variable r

        printf("\nDoes order matter? (y/n)\n");
        printf("User: ");
        cin >> order; //'y' if order is taken into consideration(permutation)
                            //'n' if order it NOT taken into consideration(combination)

        int solution = 0; //temporary variable that represents the solution after running
                          //n and r through the permutation or combination formula

        //if user input values for n and r are in between 1 and 9, then run 
                                                //combination or permutation
        if (n_input <= 9 && n_input >= 1 && r_input <= 9 && r_input >= 1){
            if (order == 'y')
                solution = run_permutation(n_input, r_input);
            else if (order == 'n')
                solution = run_combination(n_input, r_input);
            else
                printf("\nError. Please type 'y' or 'n' to determine if order matters.\n");

            //if n < r, run_permutation or run_combination returns 0
            if (solution == 0){
                printf("Error! You can't choose %i values at a time if there \n",
                    "are only %i total values. Type in new values next loop \n.", r_input, n_input);
            }
            else
                printf("Number of possibilities: %s", solution);
        }
        else{ //else error message if numbers are out of range...
            printf("Next loop, type in values that range from 1 to 9.\n");
        }

            //option 'q' to quit out of loop
            printf("Type 'q' to quit or enter any key to continue.\n");
            printf("User: ");
            cin >> choice;
    }

    _getch();
}

/*
Returns solved combination of parameters n and r
Takes the form: n! / r!(n-r)!
*/
int run_combination(int n, int r){
    if (n < r) //solution is impossible because you can't choose r amounnt at a time if r is greater than n
        return 0;
    int n_fac = solve_factorial(n); //n!
    int r_fac = solve_factorial(r); //r!
    int nMinusr_fac = solve_factorial(n-r); //(n-r)!

    int solve = ((n_fac) / ((r_fac)*(nMinusr_fac))); // plugging in solved factorials into the combination formula
    return solve;
}

int run_permutation(int n, int r){
    if (n < r)
        return 0;
    int n_fac = solve_factorial(n);
    int nMinusr_fac = solve_factorial(n-r); 

    int solve = ((n_fac) / (nMinusr_fac));  //plugging in factorials into permutation formula
    return solve;
}

int solve_factorial(int f){
    if (f-1==0 || f == 0){ //if parameter f is 1 or 0, return 1 
        int temp = f_value;
        f_value = 1; //reset f_value so that f_value remains 1 at the start of every new factorial
        return temp;
    }
    else{ //else multiply f_value by f-1
        f_value *= f;
        return solve_factorial(f-1);
    }
}

Ответы [ 2 ]

5 голосов
/ 11 февраля 2012

Это ошибка:

printf("Number of possibilities: %s", solution);

solution является int, а не строкой с нулевым символом в конце: используйте %d.

Используя std::cout, что является безопаснымвместо printf() предотвратила бы эту ошибку:

std::cout << "Number of possibilities: " << solution;
1 голос
/ 11 февраля 2012

Проблемная строка:

printf("Number of possibilities: %s", solution);

Вы говорите printf, что solution является char*, и поэтому он пытается разыменовать (char*)solution для печати содержимого "C-строки" (предположительно, когда solution имеет значение 5 в случае вашего конкретного сообщения об ошибке).

Измените %s на %d или используйте std::cout вместо printf, чтобы обеспечить безопасность типов и избежать такого рода проблем.

...