【问题标题】:unsigned char value in a function函数中的无符号字符值
【发布时间】:2017-04-02 19:25:18
【问题描述】:

这取自:https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() 方法,我试图了解这个函数是如何工作的。所以我在下面做了一个简化的例子。

您能解释一下 GetTime() 函数中发生了什么以及我应该将什么有价值的孩子传递给它吗?

我的目标是在 int main() 函数中获取 b 值。

到目前为止我的理解是:

pointer * a = I2C_Read(); 指向unsigned char,但是指针不能指向值,为什么不报错?

#include <stdio.h>
#include <stdlib.h>

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;   
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}

【问题讨论】:

  • 您的代码引用了一个空指针。最好使用 unsigned char 变量的地址调用GetTime,而不是使用空指针。
  • "...但是指针不能指向值" 咦???但这正是指针的用途:point 指向一个值,可以是数组元素、结构,或者像这里的 unsigned char。

标签: c


【解决方案1】:

您将指针 a 设置为 0 - 不是有效值

您需要阅读有关指针的信息 - 但同时将代码更改为

 unsigned char a = 0;   
 GetTime(&a);
 printf("Value of b is: %d\n" , a);

【讨论】:

    【解决方案2】:

    将主函数改为:

    int main()
    {
       unsigned char a = 0; //   
       GetTime(&a);  // call by reference concept
       printf("Value of b is: %d\n" , a); 
    }
    

    这将导致 b = 255 ,如果要打印字符,请替换 %d --> %c 。 也许对你有帮助。

    【讨论】:

      【解决方案3】:

      我明白了,谢谢

      1) GetTime(&a);                    // pass  in address of a.
      2) GetTime(unsigned char *a)       // takes in contents of a, at the moment = 0
      3) *a = read();                    // set contents of a to unsigned char 0b11111111 
      4) printf("Value of b: %d\n" , a); // call this from main func results in returned value b = 255
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-06
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-30
        相关资源
        最近更新 更多