【问题标题】:integer in C Get Random valueC中的整数获取随机值
【发布时间】:2015-01-27 05:51:00
【问题描述】:

我想通过 bluez API 用 C 语言编写程序

我用这个site 做教程:

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>


int main(int argc, char **argv)
{
    int dev_id = hci_get_route(NULL);
    int res_scan=NULL;
    int count;
    inquiry_info *device_info=NULL;
    res_scan = hci_inquiry(dev_id,3,255,NULL,&device_info,IREQ_CACHE_FLUSH);
    printf("%i\n",res_scan);
    for(count = 0;count < res_scan;count++)
    {
        char *name;
        printf("count Before : %i\n",count);
        ba2str(&(device_info+count)->bdaddr,&name);
        printf("count After : %i\n",count);

        printf("%s\n",&name);
    }



}

和出控制台:

2
count Before : 0
count After : 1111833143
00:17:EB:5D:1B:86

为什么count的值在ba2str(&amp;(device_info+count)-&gt;bdaddr,&amp;name);之后得到随机值?

在我链接的那个来源中,这个问题不会发生!?

【问题讨论】:

  • 你没有为name分配内存...
  • 你关心ba2str能做什么吗?

标签: c bluez


【解决方案1】:

而不是

char *name;
...
printf("%s\n",&name);

使用

char name[248] = { 0 };
...
printf("%s\n",name);

【讨论】:

  • 也可能是普通的name 而不是&amp;name
  • @JensGustedt no ba2str 两个参数都需要一个指针。
  • 是的,该上下文中的数组衰减为指针。还是您的意思是指向指针的指针? printf 调用绝对是错误的。
【解决方案2】:

您需要在将变量作为引用传递之前分配内存,最好的选择是在循环之外执行此操作。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>


int main(int argc, char **argv)
{
    int dev_id = hci_get_route(NULL);
    int res_scan=NULL;
    int count;
    char *name = (char *) malloc(248*sizeof(char));
    inquiry_info *device_info=NULL;
    res_scan = hci_inquiry(dev_id,3,255,NULL,&device_info,IREQ_CACHE_FLUSH);
    printf("%i\n",res_scan);
    for(count = 0;count < res_scan;count++)
    {
        printf("count Before : %i\n",count);
        ba2str(&(device_info+count)->bdaddr,name);
        printf("count After : %i\n",count);

        printf("%s\n",name);
    }

 free(name);

}

这样做你的代码会更快,因为你只会分配一次内存。

【讨论】:

  • 记得在使用memset之前清除ba2str
  • 为什么要在堆上分配名字?
  • 我想函数 ba2str 尝试在变量名上写一些东西,所以你需要分配它,但它也可以使用 char name[248],但总是在循环之外。
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 2021-07-03
  • 2010-11-25
  • 2013-07-06
  • 2015-03-22
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
相关资源
最近更新 更多