【问题标题】:XCode strcpy ( char *dest, io_name_t src) not copying to destXCode strcpy ( char *dest, io_name_t src) 不复制到 dest
【发布时间】:2018-06-01 22:40:30
【问题描述】:

这一定是我的一个简单错误,因此我犹豫使用“不工作”这个词。

这是我的代码,问题是从 io_name_t 变量到 char 数组的 strcpy 似乎不起作用,即没有复制数据。

定义结构以保存数据以供进一步使用:

static struct sUSBDevInfo {
    char devName[200];
    char svcPlane[200];
    char othPlane[200];
    int  isScreen;
} USBDevInfo[99];

现在填充结构:

int getUSBDevices ()
{
    int i = -1;

    CFMutableDictionaryRef matchingDict;
    io_iterator_t iter;
    kern_return_t kr;
    io_service_t device;
    io_name_t    deviceName;
    io_string_t  pathName;

    matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
    if ( matchingDict == NULL)
    {
        return ( "No match" );
    }
    /* Now we have a dictionary, get an iterator.*/
    kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
    if (kr != KERN_SUCCESS)
    {
        return (0);
    }

    /* iterate */
    while ((device = IOIteratorNext(iter)))
    {
        /* do something with device, eg. check properties */
                 /***Display the device names ***/

        kr = IORegistryEntryGetName(device, deviceName);
        if (KERN_SUCCESS != kr)
        {
            deviceName[0] = '\0';

        }
        i++;
        printf("\ndeviceName:%s",deviceName);
        strcpy(USBDevInfo[i].devName, deviceName);    /* !!! This and the following strcpy leave the dest variable unchanged !!! */
        IORegistryEntryGetPath(device, kIOServicePlane, pathName);
        strcpy(USBDevInfo[i].svcPlane, pathName);
        IORegistryEntryGetPath(device, kIOUSBPlane, pathName);
        strcpy(USBDevInfo[i].othPlane, pathName);
        USBDevInfo[i].isScreen = isScreen(deviceName);
        IOObjectRelease(device);
    }

    /* Done, release the iterator */
    IOObjectRelease(iter);
    return ( i );
}

当我调试时,它显示 deviceName 具有预期值(例如 deviceName:Root Hub Simulation Simulation),但 USBDevInfo[i].devName 的 strcpy 使目标保持不变('\0')。

编辑。

尝试过。复制到另一个局部变量有效,但不能复制到全局静态结构项:

char cpy[200];      /* local variable */
.
.
strcpy(cpy, deviceName);                   /* Works - copied to cpy */
strcpy(USBDevInfo[i].devName, deviceName); /* Not working */
USBDevInfo[i].devName[0] = deviceName[3];  /* Not working */

编辑 2

请看下面的答案。

【问题讨论】:

  • 所以如果它现在对您的“编辑 2”更改有效,还有问题吗?
  • @Michael - 是的,它现在正在工作。

标签: xcode struct strcpy


【解决方案1】:

编辑 2

修改了头文件,只包含结构的类型定义。

typedef  struct sUSBDevInfo {
    char devName[400];
    char svcPlane[400];
    char othPlane[400];
    int  isScreen;
} tUSBDevInfo;

将结构变量声明移至 C 文件。

static  tUSBDevInfo USBDevInfo[99];

现在 strcpy 可以工作了。

因此,将结构数组变量放在标头中会导致代码无法更改数组中的值,但将其放在 c 文件中(作为全局)可以。

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    • 2010-12-08
    • 2017-01-10
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多