c - C-如何在将解引用的值传递给函数以稍后与另一个字符串进行比较时获取原始值?

标签 c reference dereference

我知道家庭作业的帮助不被接受,但是,我对编码员有很深的了解。

除了帮助我了解更多内容,我还希望得到帮助。

因此,当我获取变量的地址(&c )时,我了解到已将其地址保存到内存中的位置,但是我不知道如何取消引用该地址才能访问其特定值('b'在要使用的函数( color(&c,total ))中进行比较的

由于作业要求,不能因任何原因更改电源

typedef struct dragon
{
    char *name;
    char *color[3];
    int numHead;
    int numTail;

}dragon;

void color(char* color, dragon *d);

int main()
{

dragon total[4];
dragon_info(total);
char c = 'b';
color(&c, total);
return 0;
}

最终,我用这条线看颜色是否匹配
if(strcmp(color, d[currentDra].color[currentColor]);

在我使用下面的代码之前,因为从我的第一个角度来看,
if(color ==  d[currentDra].color[currentColor])

但是经过一段时间的调试后,我意识到 color 只是一个地址

总体而言,我需要以某种方式使用地址来获取 color 的值。
*颜色找不到值。
&color也不是。

其余功能
void color(char *color, dragon *d)
{
    char *colorList[5] = {"red","blue","white","green","yellow"}; 
    int colorShow;
    int knownColor = 1;
    printf("what the fuck is color? ==== %p\n", color);
    if(*color == 'r')
    {
        colorShow = 0;
    }
    else if(*color == 'b')
    {
        colorShow = 1;
    }
    else if(*color == 'w')
    {
        colorShow = 2;
    }
    else if(*color == 'g')
    {
        colorShow = 3;
    }
    else if(*color == 'y')
    {
        colorShow = 4;
    }
    else
    {
        printf("Sorry that is an unknown color, exiting...\n");
        knownColor = 0;
    }


    //if a char then = numbers 0-1
    //one loop for the dragons
    if(knownColor)
    {
        printf("***All the %s dragons:***\n", colorList[colorShow]);
        int currentDra;
        for(currentDra = 0; currentDra < 4; currentDra++)
        {
            //another loop for the colors of the dragon
            int currentColor;
            for(currentColor = 0; currentColor < 3; currentColor++)
            {
                //printf("%c\n\n", (char*)color);

                if(strcmp(color, d[currentDra].color[currentColor]))
                {
                   printf("%s is %s\n", d[currentDra].name, colorList[colorShow]);
                }
            }
        }
    }
}

非常感谢,这是我有史以来第一个问题。

最佳答案

if(strcmp(color, d[currentDra].color[currentColor]);
这不起作用,因为传递的color并非以null终止。因此,这是 undefined 的行为。
if(color == d[currentDra].color[currentColor])
这是行不通的,因为您正在比较指针而不是它们引用的值。

如果dragon.color是包含单个字符串的数组,则可以与以下内容进行比较:
if(color[0] == d[currentDra].color[currentColor][0])

关于c - C-如何在将解引用的值传递给函数以稍后与另一个字符串进行比较时获取原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144573/

相关文章:

c++ - 在 C++ 中使用集合迭代器

c - 使用 C 播放音频文件

C:从一个完整的数组中删除,只删除重复项的第一个实例

c - g_hash_table_contains 返回意外值

pointers - 为什么 Deref::deref 的返回类型本身就是一个引用?

java - temp.compareTo 错误。 Int 不能被取消引用

c++ - "Expression: vector iterator not deferencable"运行时错误

c++ - 错误 : variable or field ‘myfunction’ declared void

python - python 中的大型对称列表 : will references contribute to size in ram?

c++ - 为什么对字符串参数的 const 引用可以采用字符串文字?