gpt4 book ai didi

c - 结构数组错误

转载 作者:行者123 更新时间:2023-11-30 21:09:52 25 4
gpt4 key购买 nike

我似乎无法理解如何从用户输入复制到数组结构中,我研究了整个网站,发现了很多变体,但没有一个对我有帮助的示例:

#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;
}

预先感谢您的帮助。

最佳答案

您使用单个字符来存储名称和状态。你没有分配内存。当您分配内存时,请使用指针表示法而不是数组,因为数组将具有无法修改的常量指针。请记住释放内存。

#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;
}

关于c - 结构数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33048521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com