我想通过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
值?在那个来源我链接这个问题不会发生!?
最佳答案
在将变量作为引用传递之前,您需要分配内存,最好的选择是在循环之外进行分配。
#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);
}
这样做你的代码将更快,因为你将分配内存只有一次。