问题描述
我正在研究 C 中结构的一些基本实现。我的程序的目标是使用变量而不是指针访问结构的成员。 这是我的程序:
#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.height);
}
在实现这一点时,我只得到了垃圾值而没有更新:
The old values are ⌡o!uC&uⁿ■a
3985408
如何使用变量更新我的结构成员?
解决方法
线
strcpy("Will Smith",DAD.name);
错了。
根据strcpy(3) - Linux manual page:
char *strcpy(char *dest,const char *src);
destination(写入副本的位置)是第一个参数,源(应该复制的内容)是第二个参数。
因此,该行应该是
strcpy(DAD.name,"Will Smith");
还使用未初始化的非静态局部变量的值调用未定义的行为,允许任何事情发生。
为了更安全,您应该在打印前初始化变量 DAD
。换句话说,这条线
struct oldvar DAD;
应该是(例如)
struct oldvar DAD = {""};
,
如其他答案所述,strcpy()
的第一个参数是 destination。另外,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};
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.height);
}
,
strcpy("Will Smith",DAD.name);
--> strcpy(DAD.name,"Will Smith");
strcpy("威尔史密斯",DAD.name);将 DAD.name 复制到一些包含“Will Smith”的常量内存(只读内存部分)。
这样,你的程序就会崩溃,因为有尝试写入只读内存部分