棘手的结构指针迭代而不给出转储

时间:2013-10-24 06:06:05

标签: c++ arrays pointers structure

棘手的结构指针迭代而不给出转储

结构指针不提供转储

#include <iostream>
#include <malloc.h>
#include <conio.h>
using namespace std;

typedef struct 
{
 int k;       

}struct1;        

typedef struct 
{
  int i;
  char *ptr;     
  int len;     
  struct1 otherinstance;
}struct2;

int func(struct2 *instance,int y)
{
    int res = 0,i=0;
    for(i=0;i<y;i++)
    {
    instance[i].otherinstance.k = 10;
    printf("Data = %d\n",instance[i].otherinstance.k);
    }    
    return res;        
}


int main()
{
 int x =3;   
 struct2 *instance1 = (struct2*)malloc(sizeof(struct2));
 func(instance1,3);  
 cin.get();  
 return 0;   
}

/*
Output:
Data = 10       
Data = 10
Data = 10       
*/

请分析以上代码。我有一个函数名称“func”,它接受指向结构的指针。 在函数“func”中,我正在迭代结构数组:“应该给DUMP”。

工具:dev c ++ windows

2 个答案:

答案 0 :(得分:2)

你的意思是你知道sizeof(instance1)应该是n * sizeof(* instance1)以及为什么它在func中没有崩溃? 这称为未定义的行为,它可以工作,因为从malloc返回的内存是有效的内存,你可以在func中访问它。尝试在发布版本和优化等方面运行它,看看它何时开始崩溃。

答案 1 :(得分:0)

未定义的行为。在sizeof(struct2)中使用malloc它会在大多数编译器中崩溃。

相关问题