struct match
{
char men[64];
char women[64];
char menNum[1000];
char woNum[1000];
};
void printOut();
int matchMaking(struct match* p, struct match* q, int k);
int main(void)
{
FILE* fin;
FILE* fout;
fin = fopen("input.txt", "r");
fout = fopen("out.txt", "w");
int matchNum = 0;
int size;
int i;
int j;
int a;
struct match* ptrName;
struct match** ptrNum;
char* str;
char temp[800];
if(fin == NULL)
printf("Cannot Find File");
fgets(temp, 800, fin);
str = (char*)malloc(sizeof(char));
str = (char*)strtok(temp, " \n");
size = atoi(str);
printf("Size = %d\n", size);
ptrName = (struct match*)malloc(size*sizeof(struct match));
ptrNum = (struct match**)malloc(size*sizeof(struct match*));
for(i = 0; i < size; i++)
{
fgets(temp, 800, fin);
str = (char*)strtok(temp, " \n");
matchNum = atoi(str);
printf("Match Num = %d\n", matchNum);
fgets(temp, 800, fin);
strcpy(ptrName->men, temp);
printf("Name = %s\n", ptrName->men);
fgets(temp, 800, fin);
strcpy(ptrName->women, temp);
printf("Name = %s\n", ptrName->women);
for(j = 0; j<matchNum; j++)
{
fgets(temp, 800, fin);
strcpy(ptrNum[j]->menNum, temp);
printf("Men Num = %d\n", ptrNum[j]->menNum);
}
调试时我不断收到段错误错误
最佳答案
粗略地说,我想说问题出在这里:
ptrNum = (struct match**)malloc(size*sizeof(struct match*));
您真正想要的是足够的内存来容纳 size
数量的 struct match
,而不是 size
数量的指针。然后您想要索引到该空间。
实际上,你应该做类似的事情
struct match* ptrNum = malloc(size*sizeof(struct match));
这将为您提供一个用于 size
个结构体的内存块,并为您提供指向第一个结构体的指针。您可以使用简写的“数组”表示法对此内存进行索引,因此 match[0]
会为您提供“数组”中位置 0 处的结构,并且 match[j]
> 为您提供第 j 个位置的记录。
另请注意,match[j]
会返回实际内存,因此您不会想使用指针表示法:
strcpy(ptrNum[j].menNum, temp);
关于c - 尝试存储指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3818243/