获取指向char的指针数组的地址

时间:2010-09-01 03:34:56

标签: c pointers

gcc 4.4.3 c89

我正在尝试显示地址。基本上,我只是想证明我正在显示正确的地址。

我想显示指向char'mevice_gc','device_mg','device_cc'

的每个指针数组的地址

所以我在主函数中显示它们。但是,在我的display_list函数中,我只是想证明我正在显示正确的地址。输出是一样的。

我希望你明白吗?

非常感谢任何建议。

#include <stdio.h>

void display_list(char ***dev_list);

int main(void)
{
    char *device_gc[] = {"GCDEV01", "GCDEV02", "GCDEV03", "GCDEV04", "GCDEV05", "GCDEV06", NULL};
    char *device_mg[] = {"MGDEV01", "MGDEV02", "MGDEV03", "GCDEV05", NULL};
    char *device_cc[] = {"CCDEV01", "CCDEV02", "CCDEV03", "CCDEV04", "CCDEV05", NULL};

    char **device_list[] = {device_gc, device_mg, device_cc, NULL};

    printf("device_gc [ %p ]\n", (void*)*device_gc);
    printf("device_mg [ %p ]\n", (void*)*device_mg);
    printf("device_cc [ %p ]\n", (void*)*device_cc);

    display_list(device_list);

    return 0;
}

void display_list(char ***dev_list)
{
    while(**dev_list != NULL) {
        printf("dev [ %p ]\n", (void*)**dev_list++);
    }
}

期望的输出:

device_gc [ 0x80485e0 ]
device_mg [ 0x8048610 ]
device_cc [ 0x8048628 ]
dev [ 0x80485e0 ]
dev [ 0x8048610 ]
dev [ 0x8048628 ]

我得到的实际输出是不同的,有时会导致核心转储。那是为什么?

1 个答案:

答案 0 :(得分:2)

两个小调整。在main()中打印值之前,不应取消引用'device_gc'等;你应该只在display_list()中使用一个解除引用:

#include <stdio.h>

void display_list(char ***dev_list);

int main(void)
{
    char *device_gc[] = {"GCDEV01", "GCDEV02", "GCDEV03", "GCDEV04", "GCDEV05", "GCDEV06", NULL};
    char *device_mg[] = {"MGDEV01", "MGDEV02", "MGDEV03", "GCDEV05", NULL};
    char *device_cc[] = {"CCDEV01", "CCDEV02", "CCDEV03", "CCDEV04", "CCDEV05", NULL};

    char **device_list[] = {device_gc, device_mg, device_cc, NULL};

    printf("device_gc [ %p ]\n", (void*)device_gc);
    printf("device_mg [ %p ]\n", (void*)device_mg);
    printf("device_cc [ %p ]\n", (void*)device_cc);

    display_list(device_list);

    return 0;
}

void display_list(char ***dev_list)
{
    while(*dev_list != NULL) {
        printf("dev [ %p ]\n", (void*)*dev_list++);
    }
}