gpt4 book ai didi

c - Dynamic Memory Allocate,处理Structure时如何正确使用指针?

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:58 24 4
gpt4 key购买 nike

我现在正在学习动态内存分配,很难理解,尤其是当讲师提到 DMA 和使用指针的结构时。

首先,在我的代码的第 1 行,我对“&ptr->eno”的含义感到困惑。我们将 ptr 作为指针启动,所以它意味着 ptr 保存我们保留的内存地址,假设 ptr 保存地址 2046,“&ptr->eno”是否意味着将值写入它指向的 2046 地址?

其次,在第 2 行,我如何打印出值,因为“ptr->eno”包含值“2046”,当我打印出来时,它会给我数字 2046,而不是我尝试的值存储在内存位置2046。

我的代码是从讲义中复制的,我试图在 Visual Studio 上运行它,但在我输入值后它崩溃了。我是 C 的新手,我的假设可能看起来愚蠢且难以理解。如果你不明白我的解释,请告诉我如何使用带结构的指针,也许我能找出我的错误。谢谢

#include<stdio.h>
#include<stdlib.h>
struct emp
{
int eno;
char ename[20];
float esal;
};
void main()
{
struct emp* ptr;
ptr = (struct emp*)malloc(sizeof(struct emp));
if (ptr=NULL)
{
printf("out of memory error");
}
else
{
printf("enter the value of employee: \n");
scanf_s("%d%s%f", &ptr->eno, ptr->ename, &ptr->esal); // line 1
}
printf("the name is: %s \t the number: %d \t the salary: %f", ptr->ename, ptr->eno, ptr->esal); //line2
}

最佳答案

假设

if (ptr=NULL)

是一个错字(因为随后的“输入值后崩溃”不可能发生),这里有一个错误:

scanf_s("%d%s%f", &ptr->eno, ptr->ename, &ptr->esal);

缺少 %s 所需的大小参数

scanf_s("%d%s%f", &ptr->eno, ptr->ename, 20, &ptr->esal);

或者不是硬编码,也许

scanf_s("%d%s%f", &ptr->eno, ptr->ename, (unsigned)sizeof ptr->ename, &ptr->esal);

关于c - Dynamic Memory Allocate,处理Structure时如何正确使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47431368/

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