Использована неинициализированная локальная переменная c как исправить

Имеется код:

Source.cpp

#include "Header.h"
int main() {
    srand(time(0));
    int n = 3;
    int m = 3;
    int maxi;
    int maxj;
    int** Mas ;
    int** Bufer ;
    initMemory(Mas , n, m);
    initMemory(Bufer ,n, m);
    Zapoln(Mas, n, m);
    cout << "Massive: " << endl;
    vyvod(Mas, n, m);
    Masscopy(Bufer, Mas, n, m);
    cout << "Copy of massive: " << endl;
    vyvod(Bufer , n, m);
    freeMemory(Mas, n);
    initMemory(Mas, n - 1, m - 1);
    int max = maxel(Bufer, n, m, maxi, maxj);
    cout << endl;
    cout << "Max element: " << "[" << maxi << "]" << "[" << maxj << "]" << "=" << max << endl;
    cout << endl;
    del(Bufer, maxi, maxj, n, m);
    vozvr(Mas, Bufer , n -1 , m -1);
    cout << "After massive: " << endl;
    vyvod(Mas, n - 1, m - 1);
    freeMemory(Bufer, n);
    delete[] Bufer;
    system("pause");
}

memory.cpp

#include "Header.h"
void initMemory(int **A, int n, int m) {
    A = new int *[n];
    for (int i = 0; i < n; i++) {
        A[i] = new int[m];
    }
}
void freeMemory(int **A, int n) {
    for (int i = 0; i < n; i++) {
        delete[] A[i];
    }
}

Array_helper.cpp

#include "Header.h"
void vyvod(int **A, int n, int m) {
    for (int i = 0; i< n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << "mas[" << i << "]" << "[" << j << "]=" << setprecision(3) << *(*(A + i) + j) << " ";
        }
        cout << endl;
    }
}
void Zapoln(int **A, int n, int m) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            *(*(A + i) + j) = rand() % 26 - rand() % 26;
        }
    }
}
void Masscopy(int** A, int** B, int n, int m) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            *(*(A + i) + j) = *(*(B + i) + j);
        }
    }
}

void del(int **A, int  maxi, int maxj, int n, int m) {
    for (int i = maxi; i < n - 1; i++) {
        for (int j = maxj; j < m - 1; j++) {
            *(*(A + i) + j) = *(*(A + i + 1) + j + 1);
        }
    }
}

Logic.cpp

#include "Header.h"
void vozvr(int** A, int** B, int n, int m) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            *(*(A + i) + j) = *(*(B + i) + j);
        }
    }
}
int maxel(int **A, int n, int m, int& maxi, int& maxj)
{
    int Max = A[0][0];
    maxi = maxj = 0;
    for (int i = 0; i< n; i++)
        for (int j = 0; j< m; j++)
            if (fabs(A[i][j]) > fabs(Max))
            {
                Max = fabs(*(*(A + i) + j));
                maxi = i;
                maxj = j;
            }
    return Max;
}

Однако при выполнении выдает ошибку:

  • 1>d:загрузкиsource.cpp(10): error C4700: использована
    неинициализированная локальная переменная «Mas»
    1>d:загрузкиsource.cpp(11): error C4700: использована
    неинициализированная локальная переменная «Bufer»

В чём проблема?

В прогу вводится двоичное число, выводится десятичное

#include <iostream>

using namespace std;

int main() {

	setlocale(LC_CTYPE, "Russian");	// добавляет русский язык в консольное приложение

	
		int num, r, a, b = 0;
		cout << "Введите число в двоичной системе:  ";
		cin >> num;

		while (num != 0) {
			a = num % 10;
			if (b == 0)
				b = 1;
			if (b != 0)
				a *= b;
			r += a;
			b *= 2;
		}
		cout << "Число в десятичной системе = ", r;
	return 0;
}

Выводит ошибку: » Использована неинициализированная локальная переменная «r» «. Только для переменной «r». Для остальных переменных ошибок не показывает.

Ilya-Glushko

0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

1

21.01.2018, 15:11. Показов 22252. Ответов 19

Метки калькулятор систем счисления (Все метки)


Студворк — интернет-сервис помощи студентам

При компиляции выдаёт вот такие ошибки:
error C4700: использована неинициализированная локальная переменная «y»
error C4700: использована неинициализированная локальная переменная «x»

P.S Пробовал переставлять объявления и менял их, не помогает.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
 
int main()
{
 
    setlocale(0, "");
    double num;
    cout << "Введите число 1 - умножение, 2 - деление. ";
    cin >> num;
    if (num = 1)
    {int a, b;
 
    cout << "Введите первое число: ";
    cin >> a;
    cout << "Введите второе число: ";
    cin >> b;
    int c = a * b;
    cout << "Результат = " << c << endl; 
    }
 
 
    else if (num = 2)
    setlocale(0, "");
    
    cout << "Введите число 2 - деление ";
    cin >> num;
    int x, y;
        int c = y / x;
    if (num = 2)
 
            
    cout << "Введите первое число: ";
    cin >> x;
    cout << "Введите второе число: ";
    cin >> y;
    cout << "Результат = " << c << endl;
    }



0



139 / 67 / 46

Регистрация: 15.10.2015

Сообщений: 308

21.01.2018, 15:21

2

Инициализируйте X и Y нулями.



0



3944 / 2858 / 665

Регистрация: 08.06.2007

Сообщений: 9,668

Записей в блоге: 4

21.01.2018, 15:23

3

Лучший ответ Сообщение было отмечено Ilya-Glushko как решение

Решение

Переставить строку 31 и поставить ее после 38-й.

Добавлено через 1 минуту

Цитата
Сообщение от Reavolt
Посмотреть сообщение

Инициализируйте X и Y нулями.

Это приведет к делению на нуль в строке 38.



1



139 / 67 / 46

Регистрация: 15.10.2015

Сообщений: 308

21.01.2018, 15:25

4

Цитата
Сообщение от palva
Посмотреть сообщение

Это приведет к делению на нуль в строке 38.

Ему не кто не запрещает инициализировать их 1. Я не читал код, так-как из самой ошибки понятно, в чем проблема.



1



pain1262

6 / 6 / 7

Регистрация: 24.09.2016

Сообщений: 63

21.01.2018, 15:35

5

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
 
void main()
{
    setlocale(LC_ALL, "RUS");
    int num = 0, a = 0, b = 0;
    double c = 0;
    cout << "Введите число 1 - умножение, 2 - деление. "; cin >> num;
    if (num == 1)
    {
        cout << "Введите первое число: "; cin >> a;
        cout << "Введите второе число: "; cin >> b;
        c = a * b;
        cout << "Результат = " << c << endl;
    }
    if (num == 2)
    {
        cout << "Введите первое число: "; cin >> a;
        cout << "Введите второе число: "; cin >> b;
        c = a / b;
        cout << "Результат = " << c << endl;
    }
}



0



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 15:42

 [ТС]

6

Спасибо, помогло.

Добавлено через 3 минуты
С помощью этого не произойдет деление.



0



7427 / 5021 / 2891

Регистрация: 18.12.2017

Сообщений: 15,694

21.01.2018, 16:11

7

Ilya-Glushko, сбросьте условие задачи



0



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 16:15

 [ТС]

8

Yetty, задачи поставленно небыло, я просто хотел сделать калькулятор с выбором умножения и деления, щас дорабатывать буду, кстати у меня ещё одна проблема…



0



7427 / 5021 / 2891

Регистрация: 18.12.2017

Сообщений: 15,694

21.01.2018, 16:20

9

Ilya-Glushko, дело не в инициализации (она вообще не нужна если не переназначать переменные), а в обработке возможной попытки деления на нуль.



0



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 16:40

 [ТС]

10

Yetty, Что вы предлагаете? Можете конкретно показать? Сразу оговорюсь если я использую std::, не запускается, так что не делайте на это расчет.

З.Ы Visual Studio 2017

Добавлено через 36 секунд
palva, да, помогло…



0



Yetty

7427 / 5021 / 2891

Регистрация: 18.12.2017

Сообщений: 15,694

21.01.2018, 16:41

11

Цитата
Сообщение от Ilya-Glushko
Посмотреть сообщение

Yetty, Что вы предлагаете? Можете конкретно показать?

примерно так:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
 
int main()
{    
    int n=1, num;
    double a, b, eps=0.0000000001;
        while (n==1)
{
        cout << "a="; cin >> a;
        cout << "b="; cin >> b;
        do
    {  
        cout << "1x or 2: "; cin >> num;
        if (num!=1 && num!=2) cout <<"Enter error/Repeat please.";
    }
    while (num!=1 && num!=2);
    if (num == 1) cout <<"c="<<a * b;
    if (num == 2 && (b<-eps || b>eps)) cout <<"c="<<a / b;
    if (num == 2 && b>-eps&& b<eps) cout <<"Error division by zero";
   cout <<"nContinue? (1 - YES) "; cin >>n;
}       
    system("pause");
    return 0;
}

переменную с не использовал (только вывод результата) — если она нужна сообщите



1



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 16:42

 [ТС]

12

Yetty, Спасибо, завтра попробую с этим. Сейчас времени уже нету) Если что, обращусь к вам.



0



139 / 67 / 46

Регистрация: 15.10.2015

Сообщений: 308

21.01.2018, 16:43

13

Цитата
Сообщение от Ilya-Glushko
Посмотреть сообщение

если я использую std::, не запускается

Это еще что за магия?



0



Ilya-Glushko

0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 16:43

 [ТС]

14

Reavolt,

C++
1
using namespace std;



0



139 / 67 / 46

Регистрация: 15.10.2015

Сообщений: 308

21.01.2018, 16:44

15

Ilya-Glushko, Я имел в виду то, как программа может не работать с указыванием пространства имён?



0



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 16:46

 [ТС]

16

Reavolt, Сам задаюсь этим вопрос, штука в том, что при отсутсвии «using namespace std;» не запускается, а при присутствии и указании «std::» тоже выдает ошибку, даже на примерах из обучения.



0



139 / 67 / 46

Регистрация: 15.10.2015

Сообщений: 308

21.01.2018, 16:48

17

Ilya-Glushko, Если вы указываете пространство имен напрямую std::cout… то вам вообще не нужен using namespace std;



0



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 16:50

 [ТС]

18

Reavolt, Указыва и убирать using namespace std; пробовал, одно и тоже.



0



7427 / 5021 / 2891

Регистрация: 18.12.2017

Сообщений: 15,694

21.01.2018, 17:25

19

Ilya-Glushko, самостоятельно добавьте в калькулятор возможность сложения, вычитания и возведения в степень (включив в программу дополнительную библиотеку #include <cmath>)



1



0 / 0 / 0

Регистрация: 21.01.2018

Сообщений: 11

21.01.2018, 17:31

 [ТС]

20

Yetty, спасибо, попробую!



0



When I write this code and compile with /W4

long r;
__try { r = 0; }
__finally { }
return r;

I get:

warning C4701: potentially uninitialized local variable 'r' used

Why does this happen?

asked Apr 23, 2012 at 16:50

user541686's user avatar

user541686user541686

204k126 gold badges522 silver badges880 bronze badges

The compiler can’t be sure the code inside of the try block will successfully run. In this case it always will, but if there’s additional code in the try block r = 0 may never execute. In that case r is uninitialized hence the error.

It’s no different than if you said:

long r;
if(something) {
  r = 0;
}
return r;

(where ‘something’ is pretty much anything other than a constant true value).

answered Apr 23, 2012 at 17:52

JonBWalsh's user avatar

5

Adding this as an answer as it is of more interest than in just a comment:
The error never appeared until a labeled-statement: was inserted before the variable. Remove the goto & associated label and there is no warning.
This might have something to do with how namespace pathing is setup with a similar warning C4702 generated on a line number before the insertion of a goto block. MVCE still to be generated if anyone is interested.

answered Feb 18, 2016 at 20:46

Laurie Stearn's user avatar

Laurie StearnLaurie Stearn

9611 gold badge12 silver badges33 bronze badges

1

Because long r; creates r but it is not initialized; it is null.

So it warns you that the variable is not initialized. In certain cases it will cause Null Pointers.

answered Apr 23, 2012 at 16:52

Sully's user avatar

SullySully

14.6k5 gold badges54 silver badges79 bronze badges

0

Перейти к контенту

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Warning (level 1 and level 4) C4700

Compiler Warning (level 1 and level 4) C4700

08/30/2022

C4700

C4700

2da0deb4-77dd-4b05-98d3-b78d74ac4ca7

uninitialized local variable ‘name‘ used

Remarks

The local variable name has been used, that is, read from, before it has been assigned a value. In C and C++, local variables aren’t initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.

To fix this issue, you can initialize local variables when they’re declared, or assign a value to them before they’re used. A function can be used to initialize a variable that’s passed as a reference parameter, or when its address is passed as a pointer parameter.

The /sdl (Enable Additional Security Checks) compiler option elevates this warning to an error.

Example

This sample generates C4700 when variables t, u, and v are used before they’re initialized, and shows the kind of garbage value that can result. Variables x, y, and z don’t cause the warning, because they’re initialized before use:

// c4700.cpp
// compile by using: cl /EHsc /W4 c4700.cpp
#include <iostream>

// function takes an int reference to initialize
void initialize(int& i)
{
    i = 21;
}

int main()
{
    int s, t, u, v;   // Danger, uninitialized variables

    s = t + u + v;    // C4700: t, u, v used before initialization
    std::cout << "Value in s: " << s << std::endl;

    int w, x;         // Danger, uninitialized variables
    initialize(x);    // fix: call function to init x before use
    int y{10};        // fix: initialize y, z when declared
    int z{11};        // This C++11 syntax is recommended over int z = 11;

    w = x + y + z;    // Okay, all values initialized before use
    std::cout << "Value in w: " << w << std::endl;
}

When this code is run, t, u, and v are uninitialized, and the output for s is unpredictable:

Value in s: 37816963
Value in w: 42

Не могу запустить рабочий проект под Visual Studio 2013 из-за этой ошибки. Проект старый, делался еще под Visual Studio 6.0. Видимо, там выдавалось предупреждение вместо ошибки.

Переменных много. Может быть, все-таки можно обойти эту ошибку, не инициализируя их все?

Arhadthedev's user avatar

Arhadthedev

11.4k8 золотых знаков39 серебряных знаков69 бронзовых знаков

задан 2 фев 2015 в 21:10

nezzo's user avatar

В свойствах проекта — свойства конфигурации — С/С++ — создание кода — проверка безопасности — Отключить проверку безопасности (/GS-)

ответ дан 2 фев 2015 в 21:34

nezzo's user avatar

nezzonezzo

1021 золотой знак2 серебряных знака8 бронзовых знаков

My issue is i am getting error C4700: uninitialized local variable ‘response’ used on line 26. I know it’s probably something simple I’m completely missing please help.

The local Driver’s License Office has asked you to write a program which grades the written portion of the driver’s license exam. The exam has 20 multiple choice questions. The correct answers are:

1. A 2. D 3. B 4. B 5. C 6. B 7. A 8. B 9. C 10. D 11. A 12. C 13. D 14. B 15. D 16. C 17. C 18. A 19. D 20. B

In main, declare an array and initialize it with the above correct answers. Also declare a second array for an exam taker’s answers, and get a text file name from the user.

1) have the user enter 20 answers from an exam taker and write the answers to the text file (validate that the answers are A, B, C, or D). See the 20 exam taker’s answers below.

Hint: open (and close) the file in the function.

2) read the text file of the exam taker’s answers and store them in the exam taker’s array, which was declared in main.

-a list of the numbers of the questions answered incorrectly (question numbers are 1-20).

Arrays must be processed using loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  #include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

void studentsTest(string fileName, char student_answers[], int response, int QUESTION_AMT);
void checkAnswers(char answers[], char student_answers[], int QUESTION_AMT, int MIN_CORRECT);



int main()
{
	int response;
	const int QUESTION_AMT = 20;
	const int MIN_CORRECT = 15;
	char answers[QUESTION_AMT] = { 'A', 'D', 'B', 'B', 'C', 'B', 'A', 'B', 'C', 'D', 'A', 'C', 'D', 'B', 'D', 'C', 'C', 'A', 'D', 'B' };
	char student_answers[QUESTION_AMT];


	string fileName;
	ofstream textOut;


	studentsTest(fileName, student_answers, response, QUESTION_AMT); /*I keep getting error C4700: uninitialized local variable 'responce' used*/

    checkAnswers( answers, student_answers, QUESTION_AMT, MIN_CORRECT);


	cout << endl << endl;
	system("pause");
	return (0);
}
void studentsTest(string fileName, char student_answers[], int response, int QUESTION_AMT)
{
	cout << "nPlease enter a name for your file>";
	getline(cin, fileName);

	ofstream textOut;
	textOut.open(fileName);

	for (int response = 0; response < QUESTION_AMT; response++)
	{
		cout << "Please enter your answers: " << (response + 1) << ": ";
		cin >> student_answers[response];

		while (student_answers[response] != 'A' && student_answers[response] != 'B' && student_answers[response] != 'C' && student_answers[response] != 'D')
		{
			cout << "nError! Answers must be in captial letters! ex: A, B, C";

			cout << "Please enter your answers: " << (response + 1) << ": ";
			cin >> student_answers[response];
		}
	}
	ifstream textIn;
	textIn.open(fileName);
	if (textIn.fail())
	{
		cout << "nText file not found...program will close";
		cout << endl << endl;
		system("pause");
	}
	textIn.close();
}
void checkAnswers(char answers[], char student_answers[], int QUESTION_AMT, int MIN_CORRECT)
{
	int correctAnswers = 0;

	for (int i = 0; i < QUESTION_AMT; i++)
	{
		if (answers[i] == student_answers[i])
			correctAnswers++;
	}
	cout << "nStudent must have at least 15 correct answers to pass.";
	if (correctAnswers >= MIN_CORRECT)
	{
		cout << "nYou passed the exam!";
	}
	else
	{
		cout << "nYou failed the exam!";
	}

	cout << "nThe following is the list of questions that are incorrect";
	for (int i = 0; i < QUESTION_AMT; i++)
	{
		if (answers[i] != student_answers[i])
			cout << "Question # " << i << " is incorrect! " << endl;
	}

	cout << "nCorrect Answers = " << correctAnswers << endl;
	cout << "nIncorrect Answers = " << QUESTION_AMT - correctAnswers << endl;
}

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти свою управляющую организацию
  • Составить словосочетание со словом как будто
  • Как можно найти родителей усыновленного ребенка
  • Как составить описание территории по карте
  • Как всегда найти что сказать

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии