繁体   English   中英

结构变量不能访问结构成员

[英]struct variable cannot access struct members

我正在研究 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
 

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

线

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

是错的。

根据strcpy(3) - Linux 手册页

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

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

因此,该行应该是

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

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

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

    struct oldvar DAD;

应该是(例如)

    struct oldvar DAD = {""};

如其他答案所述, 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);
}

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

strcpy("威尔史密斯",DAD.name); 将 DAD.name 复制到包含“Will Smith”的某个常量 memory(只读 memory 部分)。

这样,您的程序将崩溃,因为尝试在 READ Only Memory 部分上写入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM