我希望通过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(&(device_info+count)->bdaddr,&name);
后{{1}}获得随机值?
在那个来源我联系这个问题不会发生!?
答案 0 :(得分:5)
而不是
char *name;
...
printf("%s\n",&name);
使用
char name[248] = { 0 };
...
printf("%s\n",name);
答案 1 :(得分: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);
}
这样做你的代码会更快,因为你只会分配一次内存。