gpt4 book ai didi

c - 来自变量名的指针

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:47 29 4
gpt4 key购买 nike

我在链表中​​用字母 A 到 H 定义了节点,如下所示:

A = (struct node*) malloc(sizeof *A);

我在一个字符串中扫描,该字符串命名下一个节点和要将其更改为的变量的名称。因此,如果我写“0B”,我希望它采用字符“B”并指向具有变量名称 B 的对象:

state->zero = B;

无需显式编写函数,其中我有一系列 if 语句,可根据输入将文本输入转换为指针输出。

我该怎么做?

最佳答案

#include <stdio.h>

struct node
{
char buf[16];
};

int main()
{
node A;
node B;
node C;
node D;
node E;
node F;
node G;
node H;
char c;
node *nodes[] = {&A, &B, &C, &D, &E, &F, &G, &H};


printf("enter character (Q) to quit: ");
while ((scanf(" %c", &c) == 1) && (c != 'Q'))
{
if (c >= 'A' || c<='H') {
node* mynode = nodes[c - 'A'];
printf("mynode %p\n", mynode);
} else {
printf("Invalid\n");
}
printf("enter character (Q) to quit: ");
}
return 0;
}

关于c - 来自变量名的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28947884/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com