【发布时间】:2016-02-26 09:30:45
【问题描述】:
我正在尝试创建一个动态分配的结构类型数组,但遇到了一些问题。即程序在程序结束时在 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] = '\0';
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] = '\0';
break;
}
}
}
//fclose(hostFile);
free(ipArray);
return(0);
}
【问题讨论】:
-
sizeof(ipArray)是指针的大小,因为ipArray是指针。 -
解决了吗?我想我应该重新发布它作为答案:P
-
Aaaaand,修复了它,一段时间以来一直在强调那个。再次感谢。
-
tempFileCharVal == EOF是一个错误。EOF是int,不能安全地存储在char中。事实上,你从来没有尝试在角色中存储EOF,所以这个测试没有意义。 -
fscanf(hostFile, "%c", &tempFileCharVal) != '.'是一个错误:fscanf的返回值是成功读取的项目数,或者EOF。不会是.。在所有情况下,最好检查fscanf(...) == 1,或者甚至更好,使用fgetc而不是fscanf。
标签: c arrays dynamic struct malloc