Generally what we think is that when memory is dynamically allocated block of memory is reserved from base address to memory size , which is dynamically allocated.
But it's wrong. When memory is dynamically allocated using malloc or new , memory is allocated into HEAP so base address is getting changed.And so sometime it will result in Error , Given code is best example to understand it
Coding :-
#include<string.h>
#include<stdio.h>
#include<conio.h>
struct Student
{
char Studname[40];
float Studmark[10];
};
void setValues(struct Student* s, const char * name, float marks[], int nSubjects)
{
int i=0;
printf("Before Dynamic allocation - Address %u",s);
s = (struct Student*)malloc(sizeof(struct Student));
strcpy(s->Studname,name);
// printf("\n%s %s",name,s->Studname);
for(i=0;i<nSubjects;i++)
{
s->Studmark[i] = marks[i];
printf("%f ",s->Studmark[i]);
}
//printf("\nAfter Address %u",s);
}
int main()
{
struct Student ss[50];
char str[100];
int stud_No,sub_No,j,mark[10],i;
printf("\nEnter no of structure of student: ");
scanf("%d",&stud_No);
printf("\nEnter no. of subjects in Structure: ");
scanf("%d",&sub_No);
for(i=0;i<stud_No;i++)
{
scanf("%s",str);
for(j=0;j<sub_No;j++)
{
scanf("%f",&mark[j]);
}
setValues(&ss[i],str,mark,sub_No);
}
//printf("\nMain Address %u",&ss[0]);
ss[0];
printf("as %s",ss[0].Studname);
}
No comments:
Post a Comment