我正在学习操作数组。我将从文件中读取的元素数据存储在main()之外名为readInput()的函数中的char和int数组中。数据读取:
D E D E D E E D E E D E E D E E D E
21 32 35 59 58 16 11 29
我试图调整两个数组的大小,以使用realloc排除数组中的垃圾:我的问题:
在main()中打印char数组时,它包含正确的元素,但在数组末尾打印垃圾。我注意到它在readInput()上正确打印。我做错了什么?
在realloc前后的readInput()和main()中,从int数组的文件中读取的元素是正确的,除了后面跟着垃圾。我做错了什么?
输出:
从readInput()中打印-重新分配前的字符数组:D E D E D E E D E E D E
从readInput()打印-重新分配前的Int数组:21 32 35 59 58 16 11 29-8421
50451-842150451-842150451-842150451-842150451-842150451-842150451-84215041-84215044
51-842150451-842150451-842150451-842150451-842150451-842150451-842150451-842150451
重新分配后从readInput()字符数组打印:D E D E E D E E D E E D E
重新分配后从readInput()打印-Int: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()-字符数组(在重新分配之后):D E D E D E D E D E D E E D E E D E═════════════
═══════════════════════════════════
════════════════════════════════════
打印自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并继续
程序上下文:
读取的数据存储在main()外部名为readInput()的函数中,char by char/int by int分别存储在char和int数组中,这些数组分别通过main()中的malloc声明和初始大小。
在数组中存储数据之后,我需要将数组的大小重新调整为文件中读取的数据的大小。
最后,要验证main也可以访问数组,请在main()和readInput()中逐个char和逐个int编写数组。
谢谢你的帮助。
修改了正确的工作代码,谢谢!

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

最佳答案

首先,警告是不可忽视的。

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

应该已经提出一个(叮当甚至给了一个错误!)因为它不符合C。它应该是:
int main() {
    ...
    char *filename = ...;

如果不使用argv,请不要声明它,并避免对命令行参数以外的任何内容使用argv
下一步:for (int j = 0; j < charArray!=NULL; j++)还将引发大量警告。首先比较jcharArray(已经没有定义的行为)。在看到结果之后,j < charArray碰巧是真的(C中的值1),并且您将其与NULL(avoid *)进行比较!1 != 0总是正确的,你得到了一个永无止境的循环。
for (int j = 0; j < charSize || readValueArray[j] != NULL; j++)还应发出警告:readValueArray[j]是一个int并且NULL是一个void *。此外,测试readValueArray[j]0是没有用的,因为您从未初始化分配的内存。
最后,resize不会从数组中移除垃圾,它会在内存中的某个位置重新分配具有所请求大小的数组,并且如果访问超过分配的内存,则只调用未定义的行为。在C语言中没有办法知道数组的大小,这是程序员的工作来关心它。
所以你有两种可能的方法:
将数组的实际大小作为readInput的(输出)参数传递:
void readInput(char *choiceArray, int *valueArray, FILE **inputFilePointer,
    int *choiceArraySize, int *valueArraySize)

或者使用特殊值(例如0)作为结束标记。
请注意警告!

10-06 01:54