Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the pointers of a static function

I am new to C and C++. I have defined a static function which has a pointer 'ptr'. How can I access the pointer outside the function?

#include <iostream>

using namespace std;

static void accessArr(uint8_t arr[]);

int main()
{
    uint8_t arr[] = {1,2,3,4,5};

    accessArr(arr);
    
    cout << *ptr <<endl;
    return 0;
}

void accessArr(uint8_t arr[])
{
    uint8_t *ptr = arr;
}

I am getting the below error for the above code. Please help in solving the error.

main.cpp:12:14: error: ‘ptr’ was not declared in this scope

     cout << *ptr <<endl;
              ^~~
like image 992
Beginner Avatar asked Dec 18 '25 21:12

Beginner


1 Answers

The name ptr is not declared and visible in main. Just declare the function as returning a pointer like for example

static uint8_t * accessArr(uint8_t arr[])
{
    return arr;
}

And in main you can write

cout << *accessArr( arr ) <<endl;

Or

uint8_t *ptr = accessArr( arr );

cout << *ptr <<endl;
like image 113
Vlad from Moscow Avatar answered Dec 20 '25 10:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!