简体   繁体   中英

C++ Visual Studio 2010 how to use a char type variable in different functions

I'm having a problem regarding a char type variable in my program. I don't post the code because it is too long but this is roughly what I want to do:

#include ...

char path[100];

int main()
{
    char path[100] = "C:/......";

    [...]

    out = function();
}

int function()
{
    [...]
    imwrite(path,image);
    [...]

} 

The problem is that my path variable seems to be lost somehow because if I try cout < < path before imwrite in function it doesen't print anything as if path was empty.

What should I do forbeing able to access my path variable in function?

You are defining the path variable within the scope of your main function, as well as in the global scope.

In main() you have a new declaration of path :

char path[100] = "...";

This effectively gives you two variables with the same name, but in different scopes. If you access path from within the main method, it will access the locally-scoped variable.

If you wish to keep it this way, and remove the globally-scoped path variable, you could redeclare your function to:

int function(char* p_path)
{
    imwrite(p_path, image);
}

and pass the value as a parameter from main:

char path[100] = "...";
...
function(path);

As an aside, you could force access of the globally-scoped variable from within the main method by referencing ::path , which specifies the global namespace. But that's another story.

You're defining a global variable path (in global scope) and a local variable path in main() . This means that inside main() , path refers to the local one, while in function() , it refers to the global one.

If the path is hardcoded (as in the example you gave), you can do this:

#include ...

char path[100] = "C:/......";

int main()
{
    [...]

    out = function();
}

If the path needs to be computed, do this instead:

#include ...

char path[100];

int main()
{
    [...]
    std::copy(computedPathValue, computedPathValue + computedPathLength + 1, path);

    out = function();
}

Of course, the best would be to have std::string path instead of a char[100] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM