简体   繁体   中英

How can I declare a global pointer to unsigned char array and modify the value?

My main requirement is to declare an array and a pointer to it that can be read from and written to from functions throughout my program. So far I have done something like this, (Note, I even tried with pointer-to-pointer.

unsigned char *array_ptr;
unsigned char **array_ptr_ptr;
unsigned char array[20];

array_ptr = array;
array_ptr_ptr = &array_ptr;    

void main()
{
}

And then in another source file, I have a function

function(unsigned char *array_ptr)
{
    *array_ptr = value;
    array_ptr++;
    *array_ptr = value2;
}

I even tried with pointer to pointers.

function(unsigned char **array_ptr_ptr)
{
    **array_ptr_ptr = value;
    array_ptr_ptr++;
    **array_ptr_ptr = value2;
}

I cant seem to successfully write values, and even printing the values causes me issues. I also get segmentation faults.

Also, in a case such as mine, do I allocate memory using malloc to the array or the pointer?

There is no need to use a double pointer. That most likely isn't working because the other source file doesn't have an include for the file where array_ptr is declared. I think best practice is to create a globals.h file and have it reference throughout the program.

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