什么时候应该在C中使用双间接寻址?有人能举例说明吗?

我知道的是,双间接寻址是指向指针的指针.为什么我需要指向指针的指针?

推荐答案

如果你想要一个字符列表(一个单词),你可以使用char *word

如果你想要一个单词列表(一个句子),你可以使用char **sentence

如果你想要一个句子列表(独白),你可以使用char ***monologue

如果你想要一份独白 list (传记),你可以用char ****biography

如果你想要一个传记列表(一个生物库),你可以使用char *****biolibrary

如果你想要一个生物库列表(lol),你可以使用char ******lol

... ...

yes, I know these might not be the best data structures


一个非常无聊的lol的用法示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int wordsinsentence(char **x) {
    int w = 0;
    while (*x) {
        w += 1;
        x++;
    }
    return w;
}

int wordsinmono(char ***x) {
    int w = 0;
    while (*x) {
        w += wordsinsentence(*x);
        x++;
    }
    return w;
}

int wordsinbio(char ****x) {
    int w = 0;
    while (*x) {
        w += wordsinmono(*x);
        x++;
    }
    return w;
}

int wordsinlib(char *****x) {
    int w = 0;
    while (*x) {
        w += wordsinbio(*x);
        x++;
    }
    return w;
}

int wordsinlol(char ******x) {
    int w = 0;
    while (*x) {
        w += wordsinlib(*x);
        x++;
    }
    return w;
}

int main(void) {
    char *word;
    char **sentence;
    char ***monologue;
    char ****biography;
    char *****biolibrary;
    char ******lol;

    //fill data structure
    word = malloc(4 * sizeof *word); // assume it worked
    strcpy(word, "foo");

    sentence = malloc(4 * sizeof *sentence); // assume it worked
    sentence[0] = word;
    sentence[1] = word;
    sentence[2] = word;
    sentence[3] = NULL;

    monologue = malloc(4 * sizeof *monologue); // assume it worked
    monologue[0] = sentence;
    monologue[1] = sentence;
    monologue[2] = sentence;
    monologue[3] = NULL;

    biography = malloc(4 * sizeof *biography); // assume it worked
    biography[0] = monologue;
    biography[1] = monologue;
    biography[2] = monologue;
    biography[3] = NULL;

    biolibrary = malloc(4 * sizeof *biolibrary); // assume it worked
    biolibrary[0] = biography;
    biolibrary[1] = biography;
    biolibrary[2] = biography;
    biolibrary[3] = NULL;

    lol = malloc(4 * sizeof *lol); // assume it worked
    lol[0] = biolibrary;
    lol[1] = biolibrary;
    lol[2] = biolibrary;
    lol[3] = NULL;

    printf("total words in my lol: %d\n", wordsinlol(lol));

    free(lol);
    free(biolibrary);
    free(biography);
    free(monologue);
    free(sentence);
    free(word);
}

输出:

total words in my lol: 243

C++相关问答推荐

uintPtr_t上的算术

Zig将std.os.argv转换为C类型argv

C:gcc返回多个错误定义,但msvc—不""'

intellisense不工作,甚至已经下载了c/c++扩展

与unions 的未定义行为

为什么我得到更多的256假阳性在PKZIP解密密钥验证?

DPDK-DumpCap不捕获端口上的传入数据包

使用GOTO从多个嵌套循环C继续

C lang:当我try 将3个或更多元素写入数组时,出现总线错误

Clang警告称,`ffi_type`与`sizeof`不兼容

为什么指针运算会产生错误的结果?

为什么函数是按照定义的顺序执行的,而不是按照从avr-c中的int main()调用的顺序执行的?

使用TCL C API导航到列表中的元素

使用ld将目标文件链接到C标准库

使用Open62541向OPCUA服务器发送读请求时内存泄漏

将非连续物理内存映射到用户空间

为什么我无法访问C语言中的文件

Linux/C:带有子进程的进程在添加waitid后都挂起

struct 中的qsort,但排序后的 struct 很乱

SSE 向量与 Epsilon 的比较