help me --Jack

THANKS
JACK
Last edited on
closed account (Dy7SLyTq)
1
2
3
4
5
6
7
8
void foo(bool deletedynamic = false)
{
    static char *bar = new char[SomeInt];

    //perform magic

    if(deletedynamic) delete bar;
}
You could create a class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class C
{
public:

    C() = default;
    ~C(){if (bar) delete [] bar;}

    void foo()
    {
        if (bar == nullptr)
            bar = new char[0xBEEF];
        // ...
    }

    char *bar = nullptr;

};


This would allow you to create multiple instances.

Or you could simply pass an std::unique_ptr<> into the function using std::move.
closed account (Dy7SLyTq)
he still has to keep it in scope with static and then that resource is wasted because i dont think you can free static memory unless its been dynamically allocated
What exactly do you mean?

Within the class, the field bar pointer would always be in-scope of the methods.

Likewise would sending in a pointer to a function be in-scope.

Perhaps I am misunderstanding you.
closed account (Dy7SLyTq)
oh i see. you want to wrap the whole thing in the class. i was thinking you just meant a basic class to use in the function
TEST
Last edited on
help
closed account (D80DSL3A)
Your question is too vague to answer. Can you give an example of how this function would be used? Would the function return a pointer so the data allocated within the function can be used elsewhere in the program?

A function allocating data which just remains locked in the function would be pointless. We need more info. about what you're trying to accomplish.
THANK U
Last edited on
help?
You could send a char *ptr as a reference argument, check for nullptr inside the function, and allocate data if it is a nullptr. When the function returns, you will have a pointer that can be used outside the function. Would be easier using classes I believe tho...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void foo(char *(&ptr))
{
    if (!ptr)
    {
        ptr = new char[32];
    }

    ptr[3] = 'A';
}

int main()
{
    char *bar = nullptr;
    foo(bar);
    std::cout << bar[3] << std::endl;
}
closed account (Dy7SLyTq)
the op originally asked how he could allocate memory for a character and not have it go out of scope (or something of that nature)
Topic archived. No new replies allowed.