scanf更改其他字符串的值

Ron*_*ied 0 c arrays scanf

我主要使用Java开发软件,但是目前我正在尝试使用C语言中的一些东西而且我遇到了一个奇怪的问题.

我使用该scanf()方法更改字符串中的值,但scanf()不会更改参数化字符串中的值,它也会更改其他字符串中的值.

现在我的问题是:我只是从开发人员友好的Java中被宠坏了而且我太笨了而无法使用它?我没有看到我在做错的地方.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   char lFileType[] = ".txt";
   char lFilePath[] = "C:\\Notenverwaltungssystem";
   char lFileFinalPath[] = "";
   char lFileName[] = "";

    printf( "lFileType before scanf: " );
    printf( "%s \n", lFileType );

    printf( "lFilePath before scanf: " );
    printf( "%s \n", lFilePath );

    printf( "lFileName before scanf: " );
    printf( "%s \n", lFileName );

    printf( "lFileFinalPath before scanf: " );
    printf( "%s \n\n", lFileFinalPath );

    printf( "Bitte geben Sie den Namen der Pruefung an: \n\n" );

    scanf( "%s", &lFileName );

    printf( "\nlFileType after scanf: " );
    printf( "%s \n", lFileType );

    printf( "lFilePath after scanf: " );
    printf( "%s \n", lFilePath );

    printf( "lFileName after scanf: " );
    printf( "%s \n", lFileName );

    printf( "lFileFinalPath after scanf: " );
    printf( "%s \n\n", lFileFinalPath );

  system("PAUSE");  
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

lFileType before scanf: .txt
lFilePath before scanf: C:\Notenverwaltungssystem
lFileName before scanf:
lFileFinalPath before scanf:
Bitte geben Sie den Namen der Pruefung an:
Test
lFileType after scanf: .txt
lFilePath after scanf: C:\Notenverwaltungssystem
lFileName after scanf: Test
lFileFinalPath after scanf:

Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

我执行程序时得到的输出结果:

lFileType before scanf: .txt
lFilePath before scanf: C:\Notenverwaltungssystem
lFileName before scanf:
lFileFinalPath before scanf:

Bitte geben Sie den Namen der Pruefung an:
Test
lFileType after scanf: .txt
lFilePath after scanf: st
lFileName after scanf: Test
lFileFinalPath after scanf: est

Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 7

当您定义这样的字符串时:

char lFileName[] = "";
Run Code Online (Sandbox Code Playgroud)

它只分配了一个字节(用于终止'\0').它相当于:

char lFileName[1] = "";
Run Code Online (Sandbox Code Playgroud)

如果你尝试通过这个字符串读取内容,scanf那么你将获得缓冲区溢出.

将此(和类似的定义)更改为例如

char lFileName[PATH_MAX] = "";
Run Code Online (Sandbox Code Playgroud)

(请注意,您可能需要#include <limits.h>在progaram的开头附近才能获得定义PATH_MAX).


还有一点:当scanf你传递一个字符串时,你不需要取消引用它,所以:

scanf( "%s", &lFileName );
Run Code Online (Sandbox Code Playgroud)

应该只是:

scanf( "%s", lFileName );
Run Code Online (Sandbox Code Playgroud)

(对于简单的标量类型,例如int或者float您需要传递指向变量的指针,这对于C新手来说可能会造成混淆.)