繁体   English   中英

在结构中使用结构..不能访问内部结构元素?

[英]Using structure in structure..unable ot access inner structure elements?

嗨朋友我是新手并且正在尝试学习结构...这里我已经在结构计算中声明了结构日期...但是没有了解如何从日期访问元素。 我已经通过使用malloc作为父结构calc ...来保留内存,这对于日期结构也是如此? 。请指导我...谢谢!

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

struct date{
   int day;
   int month;
   int year;
};

struct calc{
   int row;
   int col;
   char menu_name[20];
   char sub_menu_name[20];
   struct date dob;
};

int main()
{
    int count = 0, i;
    struct calc *my_calc[2];

   //here unable to understand that where i need to resever seprate memory for date?
   my_calc[0] = (struct calc *)malloc(sizeof(struct calc)); 

   //trying to asign the date value 
   for(count; count<2; count++)
   {   
       printf("Please enter day: ");    
       scanf("%d",&my_calc[count]->date.day);

       printf("Please enter month: ");    
       scanf("%d",&my_calc[count]->date.month);

       printf("Please enter Year: ");    
       scanf("%d",&my_calc[count]->date.year);
   }

   //trying to print the date value 
   printf("Day: %d\t  Month: %d\t   Year: %d\n ",my_calc[0]->date.day,my_calc[0]->date.month,my_calc[0]->date.year);

   system("PAUSE");

   return 0;
}

你宣布dob不是date &my_calc[count]->dob.day

您需要使用dob ,而不是date ,例如:

scanf("%d",&my_calc[count]->dob.day);

要访问的元素的名称是dob - date是结构名称。

通过此修改,您的代码编译良好,但您将遇到一些严重的运行时问题 - 请参阅有关如何正确分配内存的提示的其他答案。

如果你是malloc sizeof(struct calc)那么它包括那个结构的所有元素(读取:它对结构的所有元素执行sizeof并将其相加并根据空间分配空间)。

我还在代码中看到了很多指针/数组问题,你应该真正阅读这个主题。

你需要通过元素dob的名称来引用,而不是元素的strcut名称( date

暂无
暂无

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

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