简体   繁体   English

如何声明指向无符号字符数组的全局指针并修改值?

[英]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? 另外,在我的情况下,我是否使用malloc将内存分配给数组或指针?

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. 这很可能无法正常工作,因为另一个源文件没有声明array_ptr的文件的include I think best practice is to create a globals.h file and have it reference throughout the program. 我认为最佳做法是创建一个globals.h文件,并在整个程序中引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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