从文件中读取int和char数组,然后调整数组

时间:2017-12-13 07:13:27

标签: c arrays windows malloc realloc

我正在学习操纵数组。我将从文件中读取的元素数据元素数据存储到名为readInput()的main()外部的函数中的char和int数组中。数据读取:

D E D D E E E E E E E E

21 32 35 59 58 16 11 29

我尝试调整两个数组的大小以使用realloc排除数组中的垃圾:我的问题:

  • 在main()中打印char数组时,它包含正确的元素,但在数组末尾打印垃圾。我注意到它在readInput()中正确打印。我做错了什么?

  • 在realloc之前和之后的readInput()和main()中,从int数组的文件中读取的元素是正确的,除了它们后面是garbage。我做错了什么?

输出:

从readInput()打印 - 重新分配前的字符数组:D E D D E E E E E E E

从readInput()打印 - 在realloc之前的Int数组:21 32 35 59 58 16 11 29 -8421 50451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -8421504 51 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451

从readInput()打印 - 重新分配后的字符数组:D E D D E E E E E E E

从readInput()打印 - Int在realloc之后:21 32 35 59 58 16 11 29 -336860 19 -842150451 739749649 37763 4849560 4849264 -842150451 -842150451 -842150451 - 842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842

从main打印() - Char数组(重新分配后):D E D D E E E E E E E =══════════════════════════(=) ════════════════════════════²²²²³£Î`瓦特º É·yÉVt = = = = = = = = / = = = = = = / = = / = = / = = = / = = / = / = = / = = / = = / = / = = / = / = / / / / / / /&#

从main()打印 - Int数组(重新分配后):21 32 35 59 58 16 11 29 -33686019 -842150451 874388096 31426 6946712 6946416 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451它继续

该计划的背景: 读取数据存储在名为readInput()的main()外部的函数中,char中的char / int由char分别存储到char和int数组中,这些数组通过main()中的malloc声明并初始调整大小。

在数组中存储数据后,我需要将数组的大小重新调整为文件中读取的数据大小。

最后,要验证main是否也可以访问该数组,请使用char和int通过int在main()和readInput()中的数组中写入char。

感谢您的帮助。 编辑了正确的工作代码,谢谢!

#include <stdio.h>
#include <ctype.h>
#include <string.h>

//prototypes
void openFile(char *fileNames, FILE **inputFilePointer);
void closeFile(FILE **inputFilePointer);
void readInput(char *choiceArray, int *valueArray, int *charArraySize, int *intArraySize, FILE **inputFilePointer);
void memCharReallocation(char **choiceArray, int requiredArraySize);//resize char array to what's actually required after reading the file
void memIntReallocation(int **valueArray, int intSize);//resize int array to what's actually required after reading the file

void main()
{
    char *charArray =NULL;
    int *valueArray;
    int inputSize;
    int charInputSize = 0;//size of elements read from file
    int intInputSize = 0;//size of elements read from file

    //file read/write variables
    FILE *iFilePointer;//file pointer
    char *filename = "inputFileTest.txt";

    //open and read Files
    openFile(filename, &iFilePointer);

    //initial mem allocation to size char and int array
    valueArray = (int*)malloc(sizeof(int) * 100);
    if (valueArray == NULL)
    {
        printf("\nCould not allocate memory, exiting.\n");
        exit(1);
    }

    charArray = (char*)malloc(sizeof(char) * 100);
    if (charArray == NULL)
    {
        printf("\nCould not allocate memory, exiting.\n");
        exit(1);
    }
    //read file and allocate to array
    readInput(charArray, valueArray, &charInputSize, &intInputSize, &iFilePointer);

    //print char array: Test I can read it here too
    printf("\nPrint from main() - Char Array: ");
    for (int j = 0; j<charInputSize; j++)
    {
        printf("%c ", charArray[j]);
    }
    //Print int array
    printf("\nPrint from main() - Int Array: ");

    for (int j = 0; j<intInputSize; j++)
    {
        printf("%d ", valueArray[j]);
    }
}

//read data from file
void readInput(char *readCharArray, int *readValueArray, int *charArraySize, int *intArraySize, FILE **inputFilePointer)
{
    int i, j = 0;//loop variables
    char *pbuffer = NULL;//buffer to read input file
    int bufferSize = 200;//max initial size for buffer
    char *token = NULL;////tonize
    char ch = NULL;//convert string char to char
    int readingChar = 0;//flag we are reading char from file

    //alloc memory to pbuffer
    pbuffer = (char*)malloc(sizeof(char)*bufferSize);
    if (pbuffer == NULL)
    {
        printf("\nCould not allocate memory, exiting.\n");
        exit(1);
    }

    printf("Read Input From File: \n");
    //store each element from file in struct variable
    while (fgets(pbuffer, bufferSize, *inputFilePointer) != NULL)//read each line from file
    {
        j = 0;//reset array to subscript zero on each pass
        //tokenize file data
        for (token = strtok(pbuffer, " "); token != NULL; token = strtok(NULL, " "))
        {
            //char token
            if (isalpha(token[0]))
            {
                ch = token[0];
                readCharArray[j++] = ch;
                readingChar = 1;//flag we are reading char from file to get length of array excl array garbage
            }
            //int token
            else if (isdigit(token[0]))
            {
                readValueArray[j++] = atoi(token);
                (*intArraySize)++;
            }

            else
            {
                printf("\nCan't read file\n");
                exit(1);
            }
        }
        if (readingChar)
        {
            readCharArray[j] = '\0';//remove excess cells on array
            *charArraySize = strlen(readCharArray);//size of array
            readingChar = 0;//end of reading char from file
        }
    }

    //print char array: Test 1
    printf("\nPrint from readInput() - Char Array before realloc: ");
    for (int j = 0; j < *charArraySize; j++)
    {
        printf("%c ", readCharArray[j]);
    }
    //Print int array
    printf("\nPrint from readInput() - Int Array before realloc: ");
    for (int j = 0; j < *intArraySize; j++)
    {
        printf("%d ", readValueArray[j]);
    }

    memCharReallocation(&readCharArray, charArraySize);
    memIntReallocation(&readValueArray, intArraySize);

    printf("\nPrint from readInput() - Char Array after realloc: ");
    for (int j = 0; j < *charArraySize; j++)
    {
        printf("%c ", readCharArray[j]);
    }
    printf("\nPrint from readInput() - Int After after realloc:");
    for (int j = 0; j < *intArraySize; j++)
    {
        printf("%d ", readValueArray[j]);
    }
}

void memCharReallocation(char **charArray, int requiredArraySize)//resize int array to what's actually required after reading the file
{
    char *ptempArray = NULL;

    ptempArray = (char*)realloc(*charArray, requiredArraySize * sizeof(char*));

    if (ptempArray == NULL)
    {
        printf("Could not allocate memory, exiting");
        exit(1);
    }
    else
        *charArray = ptempArray;

    if (ptempArray != *charArray)
        free(ptempArray);
}

void memIntReallocation(int **valueArray, int intSize)//resize int array to what's actually required after reading the file
{
    int *ptempArray = NULL;

    ptempArray = (int*)realloc(*valueArray, intSize* sizeof(int*));

    if (ptempArray == NULL)
    {
        printf("Could not allocate memory, exiting");
        exit(1);
    }
    else
        *valueArray = ptempArray;

    if (ptempArray != *valueArray)
        free(ptempArray);
}

void openFile(char *fileNames, FILE **inputFilePointer)
{
    printf("\n\n");
    //open files and error mssg
    if ((*inputFilePointer = fopen(fileNames, "r")) == NULL) {
        printf("Can't open input file %s\n", fileNames[1]);
        exit(1);
    }
}

void closeFile(FILE **inputFilePointer)
{
    //close files
    fclose(*inputFilePointer);
}

2 个答案:

答案 0 :(得分:2)

首先,警告不容忽视。

 void main(char *argv) {
        ...
        argv = ...;

应该已经提出了一个(CLang甚至会出错!)因为它不符合C.它应该是:

int main() {
    ...
    char *filename = ...;

如果不使用argv,请不要声明argv,并且除了命令行参数之外,不要使用argv

下一步:for (int j = 0; j < charArray!=NULL; j++)也应该提出大量的警告。您首先要比较jcharArray(已经未定义的行为)。看到结果后,j < charArray恰好为真(C中的值为1),并将其与NULL进行比较,即void *1 != 0永远是真的,你会得到一个永无止境的循环。

for (int j = 0; j < charSize || readValueArray[j] != NULL; j++)也应该发出警告:readValueArray[j]intNULLvoid *。此外,测试readValueArray[j]0没有用,因为您从未初始化已分配的内存。

最后调整大小不会从数组中删除垃圾它会在内存中的某个地方重新分配具有所需大小的数组,如果您访问已分配的内存,则只需调用未定义的行为。 C中无法知道数组的大小,程序员的工作就是关心它。

所以你有两种可能的方法:

  • 将数组的实际大小作为readInput的(输出)参数传递:

    void readInput(char *choiceArray, int *valueArray, FILE **inputFilePointer,
        int *choiceArraySize, int *valueArraySize)
    
  • 或使用特殊值(例如0)作为结束标记。

注意警告!

答案 1 :(得分:0)

while (fgets(pbuffer, bufferSize, *inputFilePointer) != NULL)的正文中 您使用相同的变量j作为readCharArrayreadValueArray的数组索引,我认为这会在分配期间产生问题,因为它在每次分配期间会增加一些索引值不会成为用过的。分别为readCharArrayreadValueArray使用两个变量。