Oli*_*ver 2 c pointers memory-management
在C中,一个函数可以向一个函数公开内存,它在较低级别"管理"为只调用那些调用该函数的人(暴露其地址).return * const没有效果,但我想知道我是否忽略了编程勾号?
谢谢.
const uint8_t * get_value(int index)
{
static uint8_t data[2] = {0, 0};
return (const uint8_t *)&data[index];
}
int main(void)
{
uint8_t * value;
value = get_value(1);
*value += 1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
@j_random_hacker对我的问题提出了一个很好的妥协建议,它提供了我正在寻找的额外障碍,以防止随意误用该数据.
typedef struct
{
const uint8_t * value;
const uint8_t size;
} readonly_t;
readonly_t get_value(int index, int size)
{
static uint8_t data[2] = {0, 0};
uint8_t rsize;
/* ... validate index, size params */
readonly_t r = { &data[index], rsize };
return r;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |