将char指针传递给C中的函数

时间:2015-06-30 02:26:34

标签: c arrays char

我试图通过此代码获取Mac地址:

void getMacAdress(unsigned char **address)
{
    int s;
    struct ifreq buffer;

    s = socket(PF_INET, SOCK_DGRAM, 0);
    memset(&buffer, 0x00, sizeof(buffer));
    strcpy(buffer.ifr_name, "eth0");
    ioctl(s, SIOCGIFHWADDR, &buffer);
    close(s);
    *address = (unsigned char *)buffer.ifr_hwaddr.sa_data;

    for (s = 0; s < 6; s++)
    {
        printf("%.2X ", *(*address + s));
    }

    printf("\n");
}

int main(int argc, char *argv[])
{
    unsigned char *address;

    getMacAdress(&address);
    int i;

    for (i = 0; i < 6; i++)
    {
        printf("%.2X ", *(address + i));
    }

    printf("\n");
    return 0;
}

我得到了正确的结果

08 00 27 0A 4E 98 
08 00 27 0A 4E 98

但是当我在printf函数中删除getMacAddress()代码段时,它变为:

void getMacAdress(unsigned char **address)
{
    int s;
    struct ifreq buffer;

    s = socket(PF_INET, SOCK_DGRAM, 0);
    memset(&buffer, 0x00, sizeof(buffer));
    strcpy(buffer.ifr_name, "eth0");
    ioctl(s, SIOCGIFHWADDR, &buffer);
    close(s);
    *address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
    printf("\n");
}

我得错了结果

08 00 00 00 00 00

你能解释一下为什么会这样,以及如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

问题出在这里:

*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;

buffer是函数的局部变量。因此,您在address中存储的指针指向一个局部变量,该函数在函数返回时被销毁,留下一个悬空指针。

尝试从此指针读取会导致未定义的行为。您可以根据打印时是否已将内存重新用于其他内容来解释您的输出。

答案 1 :(得分:2)

如果你想解决它......

 [['610.0', '1150.0'],['675', '1150'],['675', '1215'],['610', '1215'],['610', '1150']]

答案 2 :(得分:1)

您不能指向要在函数中返回的堆栈空间。

相反,您可以使用malloc堆空间来存储所需的结果:

void getMacAdress(unsigned char **address)
{
    int s;
    struct ifreq buffer;

    s = socket(PF_INET, SOCK_DGRAM, 0);
    memset(&buffer, 0x00, sizeof(buffer));
    strcpy(buffer.ifr_name, "eth0");
    ioctl(s, SIOCGIFHWADDR, &buffer);
    close(s);
    *address = (unsigned char*) malloc(sizeof(buffer.ifr_hwaddr.sa_data));
    memcpy(*address, buffer.ifr_hwaddr.sa_data,sizeof(buffer.ifr_hwaddr.sa_data));

    //for (s = 0; s < 6; s++)
    //{
    //    printf("%.2X ", *(*address + s));
    //}

    //printf("\n");
}

BTW,不要忘记释放主函数中的堆空间。