我刚刚使用全局变量完成了我的代码。我知道使用全局变量是不受欢迎的,所以我打算改用指针。
所以最初我的功能是 void time (void)
在函数内调用全局变量。
当我将程序更改为 void time (unsigned char *xp, unsigned char *yp, unsigned char *zp, unsigned char *ap)
后
我测试了两者(PIC16F877A)的 RAM 使用情况,令我惊讶的是,在我使用指针后,RAM 使用情况上升了。在函数不再被调用并且我正确使用它们后,这些指针将被删除(这不是问题)。有人可以向我解释这是为什么吗? 我受到了指针可以提高程序效率的影响。
附加信息(所有 4 个变量在转换为指针之前都是全局变量)。
人们要求我发布我的代码,所以这里是(这个里面有指针,我使用的是 PIC16F877A)
`void time (unsigned char *time1p, unsigned char *time2p, unsigned char *time3p, unsigned char *finishp){
unsigned char i, j=0;
unsigned char timer [] = {"Time has expired"}; //Memory saver
if (*time1p == 0 && *time2p == 0 && *time3p == 0) //if all the time is 0 finish the sequence
*finishp = 1;
if (*time1p != 0) //Checking to see if the first digit is NOT at 0
*time1p = *time1p - 1; // subtract time 1 by 1
else {*time2p = *time2p - 1; //When time1 is 0
*time1p = 9;} //Time1 going back to it's original value
if (*time2p == 0 && *time1p == 0){ //if time1 and time2 are 0s
LCD_cursor(14,0);
LCD_display_value(*time2p); //Display its value
Delay_ms(200); //Use the delay
if (*time3p != 0){ //The minute value (time3)
*time2p = 5; //60 SECONDS
*time3p = *time3p - 1;
*time1p = 9; } } //Put time 1 to its original value
//Puting the correct numbers in order
LCD_cursor(15,0);
LCD_display_value(*time1p);
LCD_cursor(14,0);
LCD_display_value(*time2p);
LCD_cursor(13,0);
LCD_putch(':');
LCD_cursor(12,0);
LCD_display_value(*time3p);
Delay_ms(300);
/*Memory saver*/
if (*finishp == 1){
LCD_clear();
while (timer[j] > 0x00)
{
LCD_putch(timer[j]); //Print the string
j=j+1;
}
for (i=0; i < 10; i++){
i=0; }
}
////////////End of memory saver
} //end of time function`
最佳答案
在小型和超小型嵌入式设备上,内存消耗的可预测性比整洁的代码重要得多,并且绝对应该优先考虑。静态分配的内存为您提供了这种可预测性。程序要么运行,要么不运行,但 2 小时后不会因为内存耗尽而崩溃。这就是为什么在小型设备上不应该真正使用动态分配的原因之一。
另一个原因是动态内存分配不是免费的 - 内存管理需要一些内存用于其自身的内部工作,并且指针通常具有架构的所有标量类型中最大的大小.
将 char 作为静态变量存储在 PIC 或 AVR 上会花费:1 个字节
在堆上存储字符需要花费:字符 1 个字节,指针 2 个字节。
想想看;)
关于c - 指针与 PIC 上 RAM 方面的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068217/