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

标签 c pointers

我现在正在学习动态内存分配,很难理解,尤其是当讲师提到 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/

相关文章:

c++ - Linux 上良好的文本文件 IO C/C++ 指南

C 编程 - Malloc 结构和未定义数组

python - 在不使用 C 函数的情况下更新 ctypes python 中结构指针的值

c++ - 指针 : p++ & p+1

c - 无法将我的应用程序服务器连接到 FCM XMPP 服务器

C2000 设备的 C 计算

C 服务器套接字 - bind() 错误

c - 为什么行不通过调用 gtk_list_store_set 函数在 TreeView 中更新

c - 将字符传递给 char *

c - 使用指针搜索特定字符串