【问题标题】:Why is this string with an outer declaration getting assigned inside the loop and reset outside it?为什么这个带有外部声明的字符串在循环内分配并在循环外重置?
【发布时间】:2023-04-01 03:38:01
【问题描述】:

我在函数中使用此代码来获取文件中最短和最长的字符串。长度变量和字符串在循环外声明。 int 变量在循环内部和外部正确更新,但 char* 变量仅在内部正确更新。

在我得到的最后一条 printf 语句中:

the string Zulia
 is the longest in a2.txt and has 18 chars

the string Zulia
 is the shortest in a2.txt and has 5 chars

这里发生了什么?

fp1 = fopen(fileName, "r"); 

        if (fp1 == NULL)
        {
            printf("Error while opening file: %s\n",fileName); 
            exit (1);
        } 



            int lengthLongestString=1;
            int lengthShortestString=1000; 

            int lengthActualString=0;

            char *longestString; 
            char *shortestString; 
            char *currentString;



        while (fgets(fileLine,  SIZE_OF_LINE, fp1) != NULL)     
        {

            if(((strcmp(fileLine, "\n") != 0)) && (strcmp(fileLine, "\r\n") != 0)){     //Validates against storing empty lines

                lineas[numeroLineas++] = strdup(fileLine);          


                             lengthActualString=strlen(fileLine); 
                             currentString=fileLine;


                             if (lengthActualString>lengthLongestString){



                                  lengthLongestString = lengthActualString;

                                  longestString=fileLine;
                                  printf("the longest string now is %s \n",longestString);

                 } 

                 else if (lengthActualString<lengthShortestString){

                     lengthShortestString = lengthActualString;


                                 shortestString=fileLine; 
                     printf("the shortest string now is %s \n",shortestString);         
                } // END IF


            }// END IF

          } //END WHILE 

          printf("the string %s is the longest in %s and has %d chars\n",longestString, fileName, lengthLongestString );
          printf("the string %s is the shortest in %s and has %d chars\n",shortestString, fileName, lengthShortestString);

【问题讨论】:

    标签: c


    【解决方案1】:

    longestStringshortestString 是指针。他们指向某个地方。如果你改变了somewhere的内容,当然,指针指向的东西已经改变了:-)

    您需要为longestStringshortestString 分配内存(或将它们定义为数组而不是指针)并将字符复制到那里。

    【讨论】:

    • 我在外面声明了 charlongestString [] 并得到一个编译错误。应该在哪里调用 malloc:在循环之前还是之后?
    • 要在外部声明一个字符数组,您需要指定一个大小char longestString[1000]。当然,您需要在复制字符时检查缓冲区溢出。 strdup 为原始副本分配了足够的内存:您应该在执行新的 strdup 之前释放它,并且当您不再需要数据时 - 或者您的程序泄漏内存。
    【解决方案2】:

    您复制了字符串,但忘记将副本分配给最短/最长的字符串变量,而是分配了指向读取缓冲区的指针。

    【讨论】:

      【解决方案3】:

      这是因为您将shortestStringlongestString 分配给fileLine。 所以你总是打印fileLine中的值,它的内容是你用fgets读取的最后一行的内容。

      你应该阅读指针。

      【讨论】:

        猜你喜欢
        • 2011-02-23
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 2014-06-15
        • 2012-10-20
        • 2010-09-27
        • 2018-01-06
        相关资源
        最近更新 更多