传递给函数后 argc 的值发生变化

问题描述 投票:0回答:0

您好,我正在研究一个基于链表的简单程序,目前该程序接受 2 个命令行参数,我需要将其传递给另一个文件中的另一个函数。然而,在传递参数之后,argc 包含一个完全不同的值。除了通过之外,我不会改变它。任何帮助将不胜感激!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "DrawTool.h"
#include "ListLib.h"
#include "FileLib.h"

#define MAX 35
#define MAP_SIZE 20

int main(int argc, char *argv[])
{
    char mapBase[MAXMAPSIZE][MAXMAPSIZE];
    int userSize;
    char drawCommand;
    int colInputNum;
    int rowInputNum;
    int lengthInputNum;
    char drawSymbol;
    char *Token;
    char Buffer[MAX];
    char letterString[MAX] = {};
    char commandString[MAX] = {};
    char tempString[MAX] = {};
    char *commandStrPtr;
    NODE *LinkedListHead = NULL;
    NODE *TempPtr = NULL;
    FILE *userFile;
    
    printf("\n the current value of argc is %d", argc);
    printf("\nThe file name should be %s", argv[1]);
    userFile = OpenFile(argc, argv);

    ReadFileIntoLinkedList(userFile, &*LinkedListHead);
    
    return 0;
} // end main

和另一个文件:

#include <stdio.h>
#include <string.h>
#include "ListLib.h"

FILE OpenFile(int argc, char *argv[])
{   
    /* declare various variables needed */
    char *fileName = NULL;
    FILE *userFile;
    printf("\n the current value of argc is %d", argc);

    /* if argc is 2, then use argv[1] as the input file name, else print the message seen in sample output */
    if(argc == 2)
    {
        printf("\nargc is 2, this should set file name");
        printf("\nThis is the second check to make sure argv[1] made it. The file name should be %s", argv[1]);
        fileName = argv[1];
    }//end if check argc
    else
    {
        printf("\nMust be run with an input file name. ");
    }//end else reject

    do
    {   

        printf("\nThe file name has made it to file lib, the name of variable fileName is:  %s", fileName);
        /* open file with "r" mode */
        userFile = fopen(fileName, "r");
        /* if file did not open */
        if(userFile == NULL )
        {
            /* print message seen in sample output */
            /* read in new filename */
            /* open the file "r" mode */
            printf("\nCould not open input file named %s\nEnter a file name at the prompt ", userFile);
            scanf("%s", fileName);
            userFile = fopen(fileName, "r");

        }
    }
    while (userFile == NULL);

    /* return the file handle */
    return *userFile;
}

(删除了不相关的片段) 这是我得到的当前输出:

 the current value of argc is 2 The file name should be input.txt the current value of argc is 1405392920 Must be run with an input file name. The file name has made it to file lib, the name of variable fileName is:  (null) Could not open input file named (null) Enter a file name at the prompt

我不确定该尝试什么,因为我是一个新手,而且我不会随时更改该值。它在 main 函数中正确读取我的命令行输入,但在按值传递后,argc 中的值完全不同。

function parameter-passing command-line-arguments
© www.soinside.com 2019 - 2024. All rights reserved.