【问题标题】:struct variable cannot access struct members结构变量不能访问结构成员
【发布时间】:2021-02-25 12:25:53
【问题描述】:

我正在研究 C 中结构的一些基本实现。我的程序的目标是使用变量而不是指针来访问 struct 的成员。 这是我的程序:

#include<stdio.h> 
#include<string.h>
struct oldvar{
    char name[100];
    int age;
    float height;
};
void main()
{   

    
    struct oldvar DAD;
    printf("\nThe old values are %s\n%d\n\f",DAD.name,DAD.age,DAD.height);
    strcpy("Will Smith",DAD.name);
    DAD.age = 50;
    DAD.height = 170;
    
    printf("The updated values are %s\n%d\n\f",DAD.name,DAD.age,DAD.height);

}

在实现这一点时,我只得到了垃圾值,没有更新:


The old values are ⌡o!uC&uⁿ■a
3985408
 

如何使用变量更新结构成员?

【问题讨论】:

  • 哇,GCC 或 Clang 似乎都没有对此发出警告!
  • @ilkkachu 他们不发出警告是正常的,因为在 C 中,字符串文字的类型是 char[] 而不是 const char[]。这很愚蠢,但我认为他们需要将其保留为非 const 以解决兼容性/可移植性问题。
  • @Jabberwocky,是的,我想可能是这样。但考虑到他们如何警告其他有效但可能是错误的东西(如if (x = y)),我不知何故希望他们也能抓住这一点——无论如何,它很可能会导致立即崩溃。也许只是这不是一个很常见的错误。
  • 啊,但是there is -Wwrite-strings! (现在我今晚可以安息了。)
  • 打印旧值而不初始化它们是未定义的行为。如果偶然没有可用的 0 字节,打印非终止字符串可能会使 printf 爬过整个内存。

标签: c variables struct member


【解决方案1】:

线

    strcpy("Will Smith",DAD.name);

错了。

根据strcpy(3) - Linux manual page:

char *strcpy(char *dest, const char *src);

destination(写入副本的位置)是第一个参数,source(应该复制的内容)是第二个参数。

因此,该行应该是

    strcpy(DAD.name,"Will Smith");

同样使用未初始化的非静态局部变量的值调用未定义的行为,允许任何事情发生。

为了更安全,您应该在打印之前初始化变量DAD。换句话说,这条线

    struct oldvar DAD;

应该是(例如)

    struct oldvar DAD = {""};

【讨论】:

    【解决方案2】:

    正如其他答案中提到的,strcpy() 的第一个参数是目的地。另外printf 也有错误。它应该是%f,而不是\f

    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h> 
    #include<string.h>
    
    struct oldvar {
        char name[100];
        int age;
        float height;
    };
    
    int main(void)
    {
        struct oldvar DAD={"\n",0,0.0};
        strcpy(DAD.name,"will Smith");
        printf("\nThe old values are %s\n%d\n%f", DAD.name, DAD.age, DAD.height);
    
        DAD.age = 50;
        DAD.height = 170;
    
        printf("The updated values are %s\n%d\n%f", DAD.name, DAD.age, DAD.height);
    }
    

    【讨论】:

    • 在答案中,您应该发布正确缩进的代码。
    【解决方案3】:

    strcpy("Will Smith",DAD.name); --> strcpy(DAD.name, "Will Smith");

    strcpy("威尔史密斯",DAD.name);会将 DAD.name 复制到一些包含“Will Smith”(只读内存部分)的常量内存中。

    因此,您的程序将崩溃,因为尝试写入只读内存部分

    【讨论】:

    • 答案应该至少提供一个简短的解释
    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    相关资源
    最近更新 更多