2015-01-31 34 views
0

我有一个虚拟函数的char *的getFileName()只返回一个指向字符数组:C了解与指针文件字符串作为名字

char * getFileName() { 
    char buff[11] = "index.html"; 
    char *p; 
    p = buff; 
    printf ("name of the file: %s\n", p); 
    return p; 
} 

在我的情况下,这个指针的名字是

int main() { 
    char *fp; 
    FILE *file; 
    fp = getFileName(); 
    int c; 
    file = fopen(fp, "r"); 
    if (file) { 
     while ((c = getc(file)) != EOF) { 
      putchar(c); 
     }  
     fclose(file); 
    } 
    return (0); 
} 

但是,我不能打开使用指针值作为名称的文件,虽然当我打印FP,我如果得到正确的名称:文件我想从主打开和读取的名字文件:index.html。任何建议,我可能会错过?谢谢:)

回答

0

您正在返回一个指向局部变量的指针 - 在getFileName()返回时,buff被销毁并且p的值指向不再可用的内存。

如果你真的想这样做,你必须做出一个buff变量static

char *getFileName(void) { 
    static char buff[] = "index.html"; 
    char *p; 
    p = buff; 
    printf ("name of the file: %s\n", p); 
    return p; 
} 

static变量没有堆栈分配;他们很好..静态分配。

其他几个重要的细节:

  • 函数f不接受应被声明为f(void)任何参数。
  • 在这种情况下,您不必明确写出buff的大小,因为您已使用"index.html"对其初始化。