C++ Reach Problem

Asked

Viewed 100 times

1

I’m a beginner in C++ programming and came across a problem when trying to execute my code on Atom, using the gpp-Compiler package and Mingw: 'Function' was not declared in this Scope (l.8). I didn’t understand the reason for the error, someone can help me?

Here is the main function:

#include <iostream>
#include "header.hpp"

using namespace std;

int main(){
    int* a;
    a = function(50);
    for(int d = 0; d < a.length; d++){
       .
       .
       .
    }
    system("pause");
    return 0;
}

and the header file:

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
#include <vector>

int* function(int num){
    std::vector<int> c;
       .
       .
       .     
    int z[(int)c.size()];
    for(int b = 0; b < (int)c.size(); b++){
        z[b] = c.at(b);
    }
    return z;
}

#endif

To be more specific, the error message was like this:

...\main.cpp: In Function 'int main()':

...\main.cpp:9:18: error: 'Function' was not declared in this Scope
a = Function(50);

...\main.cpp:10:23: error: request for Member 'length' in 'a', which is of non-class type 'int*' for(int d = 0; d < a.length; d++){

  • If I didn’t miss anything by looking over, there’s probably another mistake that’s causing this.

  • 1

    Return a array place created in the function alone is already wrong, and on a int* can’t do .length. Despite these two errors I tried to compile your code and did not get the error you indicate. How are you doing the compilation ? by hand (if yes how? ) or an IDE ? (if yes which ?)

  • Are you using Visual Studio? the #include "stdafx. h" is like the first include (or before your header)?

  • The question has been updated.

1 answer

0

To be able to return z, being a pointer have to allocate memory first

int * z = new int[(int)c.size()];

then take care to delete when the array is no longer accurate in this case in the main function.

delete a;

C++ arrays are like C, they don’t have the attribute "length" unlike java, to know the size of the array you need another way to save the size, to avoid these problems I advise you to use vector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.