如何在动态结构变量中分配动态内存?

问题描述 投票:0回答:1

我想为动态结构的成员之一动态分配一些内存。但是我不知道该怎么办,我也不知道分配后如何使用它们。

这是我的代码工作:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main()
{
    struct Sample_Structure {
        float *Number_ptr;    // This is the pointer to allocate some memory, dynamically.
        int Num1;
        int Num2;
    } *struct_ptr;

    struct_ptr = (struct Sample_Structure*) malloc (sizeof (struct Sample_Structure));
    if (!struct_ptr)
    {
        printf("An error occurred while allocating memory.\n");
        exit(1);
    }

    // I don't know what do I write here to allocate some memory to the pointer, "Number_ptr" in the structure

    printf("Enter your number 1 and 2 : ");
    scanf("%d%d", &struct_ptr->Num1, &struct_ptr->Num2);
    system("cls");

    printf("Your numbers are %d and %d\n", Struct_ptr->Num1, Struct_ptr->Num2);

    return 0;
  }

我写了一些注释,让您知道要在哪里为结构“ Sample_Structure”的指针分配一些内存。一般来说,我们可以做到吗?如果是,如何?

c
1个回答
0
投票

例如,您想为Number_ptr分配10个浮点数的内存:

struct_ptr->Number_ptr = (float*) malloc( sizeof(float) * 10 );

更正:

printf("Your numbers are %d and %d\n", Struct_ptr->Num1, Struct_ptr->Num2);
                                       ^                 ^

to

printf("Your numbers are %d and %d\n", struct_ptr->Num1, struct_ptr->Num2);
© www.soinside.com 2019 - 2024. All rights reserved.