0

I am a beginner in C++ so it's more than likely that my problem is extremely easy to solve. My problem is that I am trying to declare an array in my header file, but i can`t acces it in my main.cpp unit. The error message that keeps printing is:"initializing: cannot convert from 'int' to 'int [6]'

This is the code in my header file:

#pragma once

extern int Guess[6] = 0;

void Input(){
    std::cout << "Please enter your 6 numbers in the range of 1-49 line by line:" << std::endl;
    for (int i = 0; i < 6; i++){
        std::cin >> Guess[i];
        for (int i1 = 0; i1 < 6; i1++){
            if (Guess[i1] > 50){
                std::cout << "Your number is not in the range!!! Try again please:" << std::endl;
                Guess[i1] = 0;
                std::cin >> Guess[1];

            }
        }

    }

    std::cout << Guess[0] << std::endl;
    std::cout << Guess[1] << std::endl;
    std::cout << Guess[2] << std::endl;
    std::cout << Guess[3] << std::endl;
    std::cout << Guess[4] << std::endl;
    std::cout << Guess[5] << std::endl;
}

And this is the code in main.cpp:

#include "stdafx.h"
#include <iostream>
#include "Input.h"

int main(){

    int Guess[6];
    Input();
    return 0;
}

Thanks for any potential help.

Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • 2
    Move `int Guess[6];` outside of the `main()` function body and drop the `= 0` in the declaration. – user0042 Sep 03 '17 at 11:30
  • If you're using headers, only include declarations or inline definitions in them. `Guess` and `Input` should only be declared, with their definitions resting in a separate `cpp` file; Especially drop the `= 0` part on `Guess`. – Cubic Sep 03 '17 at 11:33
  • 1
    instead of array use std::array and pass it as a parameter (by reference) to your function - so you will not need extern or global variables – Artemy Vysotsky Sep 03 '17 at 11:35
  • Get a reasonable C++ book. [Here's the official SO list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – n. m. could be an AI Sep 03 '17 at 11:40

1 Answers1

2

You should not initialize an external array but only forward declare it. So you can declare it like this:

extern int Guess[6];

And in the another file you should define it globally:

//source.cpp

int Guess[6]; // Remove the keyword `extern` here and you must specify the size here.

void DoSomeThing(){

    // now you can use it here
    Guess[0] = 0; // eg
}
  • You can also declare the external array without specifying the size:

    // input.h
    
    extern int bigIntArray[];
    
    // source.cpp
    
    int Guess[6];
    
    void DoSomething(){
    
        // Do some staff on the array.
    }
    

This inform the compiler that the array is defined somewhere else.

Raindrop7
  • 3,889
  • 3
  • 16
  • 27