我试图创建一个类型为struct的动态分配数组,但遇到了一些问题。即程序在程序末尾的fclose命令处崩溃。在注释完这一行之后,程序在返回0时崩溃,所以我认为我的文件I/O编码有一些问题,内存分配也有问题。我的目标是用文本文件中的值填充结构宿主中包含的值。以下代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include <assert.h>
#include <stdlib.h>
typedef struct host_struct {
int x, y, z, w;
char os[8];
} host;
int main(void)
{
host *ipArray = NULL;
int numOfIps = 0;
char tempFileCharVal = 'a';
char fileString[8];
int test;
int i;
int j;
int k;
FILE *hostFile;
hostFile = fopen("hosts.txt", "r");
while (fscanf(hostFile, "%c", &tempFileCharVal) != EOF) //Nested loops to find number of ips, relies on there being a new line at the end of each IP address.
{
if (tempFileCharVal == 'n')
{
numOfIps++;
}
}
ipArray = malloc(numOfIps * sizeof(*ipArray)); //Allocates memory to array of ip addresses based on number of IP addresses and size of type host.
fclose(hostFile); //Reset hostFile to beginning of file.
hostFile = fopen("hosts.txt", "r");
for (i = 0; i < (numOfIps); i++) //Iterate through IPs, values within IPs, and values within hostFile to assign values to ipArray.
{
for (j = 0; j < 5; j++)
{
for (k = 0; fscanf(hostFile, "%c", &tempFileCharVal) != '.'; k++) //?? doesn't end loop if tempFileCharVal = '.'
{
if ((tempFileCharVal == ' ' || tempFileCharVal == 'n' || tempFileCharVal == '.') & j != 0) //?? Had to add this if statement to compensate for strange loop behavior.
{
break;
}
if ((j == 0) & tempFileCharVal == 'n')
{
fscanf(hostFile, "%c", &tempFileCharVal);
}
if ((j == 0) & (tempFileCharVal == '.' || tempFileCharVal == EOF))
{
break;
}
fileString[k] = tempFileCharVal;
}
fileString[k] = ' ';
switch (j)
{
case 0:
ipArray[i].x = atoi(fileString);
break;
case 1:
ipArray[i].y = atoi(fileString);
break;
case 2:
ipArray[i].z = atoi(fileString);
break;
case 3:
ipArray[i].w = atoi(fileString);
break;
case 4:
strcpy(ipArray[i].os, fileString);
ipArray[i].os[k] = ' ';
break;
}
}
}
//fclose(hostFile);
free(ipArray);
return(0);
}
您必须小心这一行:
ipArray = malloc(numOfIps * sizeof(*ipArray));
"ipArray"的类型为指针!不过你需要更多的内存。正确的做法是写:
ipArray = malloc(numOfIps * sizeof(struct host_struct));
编辑:我现在看到这个已经被评论了,好像我迟到了,对不起!;-)
编辑:我错了,希望我没有迷惑任何人!