我编写了这个c程序,以了解结构和指针。
问题
程序在接收输入时很有用(通过gdb测试确认),不正确的是,当打印输出数据时,它似乎被某些东西覆盖了...... 。
问题
如果编译器为某个数组保留内存,那么假设在函数“死亡”之后,预留结束,并且内存被赋予某个其他进程,是否正确?因此,这可以解释为什么结构数据被覆盖了?
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct {int marks;int roll;} ADDRESS ;
void printer(ADDRESS* pointer,int len)
{ printf("-- Entering printing mode -- \n");
ADDRESS* p1;
p1=pointer;
int counter=0;
while ( counter < len)
{
printf(" --> Entry %d \n",counter);
printf("Marks : %d \n",p1->marks);
printf("Roll : %d \n ",p1->roll);
counter++;p1++;
}
}
ADDRESS *stater(int number)
{
printf("\t STANDBY FOR INPUT PART \t \n\n\n");
ADDRESS x[number];
ADDRESS *c,*i;
c=x;
i=c;
int counterf=number;
int counter=0;
while (counter!=counterf)
{
printf("\t Input the mark : ");
scanf("%d",&(c->marks));
printf("\t Input the roll : ");
scanf("%d",&(c->roll));
printf("\n");
counter++;
c=c+1;
}
return i;
}
int main()
{
ADDRESS *o=stater(4);
printer(o,4);
return 0;
}
答案 0 :(得分:3)
释放内存后,通常会重新分配内存。当该内存存储在堆栈中时尤其如此。所以,是的。
答案 1 :(得分:1)
这适合我:
#include<stdio.h>
#include<stdlib.h>
typedef struct {int marks;int roll;} ADDRESS ;
void printer(ADDRESS* pointer,int len)
{ printf("-- Entering printing mode -- \n");
ADDRESS* p1;
p1=pointer;
int counter=0;
while ( counter < len)
{
printf(" --> Entry %d \n",counter);
printf("Marks : %d \n",p1->marks);
printf("Roll : %d \n ",p1->roll);
counter++;p1++;
}
}
ADDRESS *stater(int number)
{
printf("\t STANDBY FOR INPUT PART \t \n\n\n");
ADDRESS* x = (ADDRESS *)malloc(number*sizeof(ADDRESS));
ADDRESS *c,*i;
c=x;
i=c;
int counterf=number;
int counter=0;
while (counter!=counterf)
{
printf("\t Input the mark : ");
scanf("%d",&(c->marks));
printf("\t Input the roll : ");
scanf("%d",&(c->roll));
printf("\n");
counter++;
c=c+1;
}
return i;
}
int main()
{
ADDRESS *o=stater(4);
printer(o,4);
return 0;
}