首页 文章

为什么带有外部声明的字符串在循环内被赋值并在其外部重置?

提问于
浏览
0

我在函数中使用此代码来获取文件中最短和最长的字符串 . 长度变量和字符串在循环外声明 . 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);

3 回答

  • 0

    longestStringshortestString 是指针 . 他们 point 某个地方 . 当然,如果你改变某个地方的内容,那么指针指向的东西就会改变:-)

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

  • 1

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

  • 1

    那是因为您将 shortestStringlongestString 分配给 fileLine . 因此,您始终在 fileLine 中打印该值,该内容是您使用fgets读取的最后一行的内容 .

    你应该阅读指针 .

相关问题