gpt4 book ai didi

c - 函数结束后如何处理函数中声明的变量

转载 作者:行者123 更新时间:2023-11-30 16:16:24 30 4
gpt4 key购买 nike

我想知道以下代码中内存/变量的行为如何。基本上,我使用 epd_power_on() 将 epd_tx_buffer 添加到 epd_driver_state 中的数组中。

然后这些缓冲区通过事件驱动机制异步消耗/使用。我担心/我想知道的是,“uint8_t * buffer”指向的内存区域的内容是否是常量,或者是否有可能被覆盖。当 epd_power_on 完成时,将会执行其他代码,直到异步事件消耗缓冲区。

struct epd_tx_buffer {
uint8_t hasCmd;
uint8_t * buffer;
uint16_t bufferLen;
uint8_t wait_ms;
};

static struct epd_driver_state {
uint8_t cursor;
uint8_t length;
struct epd_tx_buffer buff[256];
bool isRunning;
} epd_driver_state;

static void epd_power_on(void){
addToSPIQueueCommandData( ( uint8_t[] ) { POWER_ON }, 1 );
addToSPIQueueCommandData( ( uint8_t[] ) { PANEL_SETTING, 0x2F }, 2 );
addToSPIQueueCommandData( ( uint8_t[] ) { PLL_CONTROL, 0x3A }, 2 );
addToSPIQueueCommandData( ( uint8_t[] ) { POWER_SETTING, 0x03, 0x00, 0x2B, 0x2B, 0x09 }, 6 );
addToSPIQueueCommandData( ( uint8_t[] ) { BOOSTER_SOFT_START, 0x07, 0x07, 0x17 }, 4);
addToSPIQueueCommandData( ( uint8_t[] ) { VCM_DC_SETTING_REGISTER, 0x00 }, 2 );
addToSPIQueueCommandData( ( uint8_t[] ) { VCOM_AND_DATA_INTERVAL_SETTING, 0x47 }, 2 );
}



bool addToSPIQueueCommandData(uint8_t * buffer, uint16_t bufferLen)
{
if( epd_driver_state.length >= 255 ) return false;
epd_driver_state.buff[ epd_driver_state.length ].hasCmd = 1;
epd_driver_state.buff[ epd_driver_state.length ].buffer = buffer;
epd_driver_state.buff[ epd_driver_state.length ].bufferLen = bufferLen;
epd_driver_state.length++;
return true;
}

一些解释将不胜感激!

最佳答案

addToSPIQueueCommandData( ( uint8_t[] ) { POWER_ON }, 1 );
addToSPIQueueCommandData( ( uint8_t[] ) { PANEL_SETTING, 0x2F }, 2 );
addToSPIQueueCommandData( ( uint8_t[] ) { PLL_CONTROL, 0x3A }, 2 );
addToSPIQueueCommandData( ( uint8_t[] ) { POWER_SETTING, 0x03, 0x00, 0x2B, 0x2B, 0x09 }, 6 );
addToSPIQueueCommandData( ( uint8_t[] ) { BOOSTER_SOFT_START, 0x07, 0x07, 0x17 }, 4);
addToSPIQueueCommandData( ( uint8_t[] ) { VCM_DC_SETTING_REGISTER, 0x00 }, 2 );
addToSPIQueueCommandData( ( uint8_t[] ) { VCOM_AND_DATA_INTERVAL_SETTING, 0x47 }, 2 );

这些是数组复合文字,一旦控制退出函数,它们就会超出范围。因此,在函数外部使用引用访问它们是未定义的行为

<小时/>

您可以考虑按如下方式进行操作。

uint8_t *temp = malloc(sizeof((( uint8_t[] ) { PLL_CONTROL, 0x3A })));
memcpy(temp, (( uint8_t[] ) { PLL_CONTROL, 0x3A }), 2);
addToSPIQueueCommandData(temp, 2);

Note: Make sure you free the memory once done processing.

关于c - 函数结束后如何处理函数中声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56602217/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com