【发布时间】:2026-01-24 16:25:01
【问题描述】:
棘手的结构指针迭代而不给出转储
结构指针不提供转储
#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”中,我正在遍历结构数组:“应该给转储”。
工具:开发 c++ 窗口
【问题讨论】:
-
神秘问题是神秘的...... 你的问题是什么?
-
1.当我传递结构指针时。为什么它在我使用结构指针数组的编译时没有给出警告/错误。
-
1.我理解未定义的行为。但是我只为一个实例分配了内存,另一个实例是如何引用函数内部的成员的。
标签: c++ arrays pointers structure