我似乎无法理解如何从用户输入复制到数组结构中,我已经在整个网站上进行了研究,我发现了很多变化,但没有一个例子可以帮助我:
#include <stdio.h>
#include <string.h>
struct member
{
char name;
int age;
char state;
};
int main()
{
int i,r,iyr;
char name, stabr;
struct member record[49];
for(r=0;r<49;r++)
{
printf ( "\nEnter the name of the family member \n");
printf ("\nCount is %d \n",r+1);
scanf ( "%s", &name);
strcpy(record[r].name, name);
printf ( "\nEnter the age of the family member \n");
scanf ( "%d", &iyr);
record[r].age=iyr;
printf ( "\nEnter the abbreviated state name of the family member \n");
scanf ( "%s", &stabr);
strcpy(record[r].state, stabr);
}
for(i=0; i<49; i++)
{
printf(" Records of Family : %d \n", i+1);
printf(" Name is: %s \n", record[i].name);
printf(" Age is: %d \n", record[i].age);
printf(" State is: %s\n\n",record[i].state);
}
return 0;
}
提前感谢您的帮助。
答案 0 :(得分:0)
您使用单个字符存储名称和状态。 你没有分配内存。 当您分配内存使用指针表示法而不是数组时,因为数组将具有无法修改的const指针。 记得释放记忆。
#include <string.h>
#include <stdlib.h>
typedef struct member
{
char name[50]; // You were using single character for storing a name of multiple character and state
int age;
char state[50];
}members;
int main(void)
{
//When you are allocating memory use pointer notation than array
//because array will have const pointer which cannot be modified
members *record = (members *)malloc(49*sizeof(members)); // you are not allocating memory
int r;
for(r=0;r<2;r++)
{
printf ( "\nEnter the name of the family member \n");
printf ("\nCount is %d \n",r+1);
scanf ( "%s", &record[r].name);
printf ( "\nEnter the age of the family member \n");
scanf ( "%d", &record[r].age);
printf ( "\nEnter the abbreviated state name of the family member \n");
scanf ( "%s", &record[r].state);
}
for(r=0; r<2; r++)
{
printf(" Records of Family : %d \n", r+1);
printf(" Name is: %s \n", record[r].name);
printf(" Age is: %d \n", record[r].age);
printf(" State is: %s\n\n",record[r].state);
}
free(record); // Remember to free the memory
return 0;
}