Hi all
I have written the code for writing values to structure and then reading from it but I am facing some problem in that.
1) When I try to read the values from stdin, it read first value correctly but for second loop it directly ask for "age" input skipping "name".
First Loop:
Enter Name:ABC
Enter Age:12
//Second Loop:
Enter Name:
Enter Age: / / Directly come here. Don't know why
2) Secondly, I am writing the code to add values in a structure by increasing the size of structure
For example,
In first loop, value stored from 1 to 100 and in second loop value should store from 101 to 200.
and at the end I assign the base address of structure to a pointer.
Ex.
.The code is as follow:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
static int count = 0;
struct test
{
int age;
char name[1000];
};
void writeToStruct(struct test **ptr)
{
int i,size_struct=0,len = 0;
struct test *p = NULL;
struct test *q = NULL;
struct test *t = NULL;
char name[1000];
if ( count != 2 )
{
size_struct = sizeof(test)*(++count);
len = sizeof(test);
p = (struct test *)malloc( sizeof(size_struct));
memcpy(p,ptr,size_struct);
t = (struct test *)malloc( sizeof(len));
printf("\n Enter Name:");
gets(name);
printf("\n Enter Age:");
scanf("%d",&i);
t->age = i;
strcpy(t->name,name);
memcpy(p+size_struct,t,len);
*ptr = p;
}
}
void readFromStruct(struct test **ptr)
{
int i =0;
for ( i =0;i<2; i++)
{
printf("\n %s %d\n",(*ptr)->name,(*ptr)->age);
}
}
int main()
{
test *t=NULL;
int i = 0;
for ( i =0;i<2; i++)
{
writeToStruct(&t);
}
readFromStruct(&t);
}
I am getting segmentation fault.
Any help is will be greatly appreciated.
Thanks