Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C4700: uninitialized local variable

Tags:

c++

console

When I compile this code it says "error C4700: uninitialized local variable 'b' used". I'm not sure what I have to do now to fix this problem. I'm neither an IT student or technican but I very like to learn C++ and I'm learning it by myself. I've been on this for 1 day.

Many thanks

#include <stdio.h>
#include <iostream>

//A. 
//1--
void InputArray(int *a, int &n)
{
    printf("Insert n = ");
    scanf("%d", &n);
    a = new int[n];
    for (int i=0; i<n; i++)
    {
        printf("Enter the key's a[%d] values: ", i);
        scanf("%d",&a[i]);
    }
}


void main()
{
    int *b, m;
    InputArray(b, m);
}
like image 468
Ben Avatar asked Dec 05 '22 07:12

Ben


2 Answers

b is passed by value, which means a copy will be made, but since it's not initialized, you get the warning. Simply initialize it:

int *b = nullptr;

or

int *b = NULL;
like image 196
Luchian Grigore Avatar answered Dec 09 '22 15:12

Luchian Grigore


If you want the function to modify the caller's variable, then pass by reference:

void InputArray(int *&a, int &n)
                     ^

Your version passes the uninitialised pointer by value; the function modifies a local copy of it, but leaves b in its uninitialised state.

like image 22
Mike Seymour Avatar answered Dec 09 '22 14:12

Mike Seymour