我刚才创建了以下代码来帮助调试我们必须编写的 C 项目,该项目基本上最终应该模拟 UNIX 文件系统。我一直在绞尽脑汁想弄清楚为什么两个看似相同的代码块会产生不同的输出。当我通过在 main() 文件中键入相同的代码行来模拟我的函数 mkfs() 应该具有的相同行为时,它工作得很好,但是当我尝试使用该函数时(字面意思是相同的代码行! !!!!!),它只是说运行失败。当我在我的 main() 函数中执行当前被注释掉的代码时,它工作得很好并且确实将“/”打印到控制台,但是当我尝试创建一个指向文件系统的指针时,调用它的 mkfs(),然后打印出相同的字符串,它只是行不通。
我一定是没听懂。这是代码,但如果您更喜欢语法高亮显示,那么这里有一个指向 pastebin 的小链接:http://pastebin.com/9yCB1iND
#include <stdio.h>
#include <stdlib.h>
typedef struct directory {
const char *name;
struct file *f;
struct directory *dir;
} Directory;
typedef struct file {
const char *name;
struct file *next;
struct file *prev;
Directory *parent;
} File;
typedef struct filesystem {
Directory *rt;
Directory *cd;
} Filesystem;
/* The function mkfs() initializes the Filesystem. It takes a pointer to a
* filesystem as its single parameter and allocates the memory needed ( it
* allocates the space needed to accomodate the two Directory pointers
* that a filesystem has). */
void mkfs(Filesystem *files){
/*The first malloc creates enough space for Filesystem itself*/
files = malloc(sizeof(Filesystem));
/*The second malloc creates enough space for a root Directory*/
files->rt = malloc(sizeof(Directory));
/*We make a character array with a single slash that represents root*/
char nv[] = "/";
/* nv is a pointer to the first element in the array nv[].
* We point 'files->rt->name' to the first character in the array nv[]. */
files->rt->name = nv;
/* Finally, we set files->cd to point to whatever files->rt pointed too,
* which is the current directory "/" */
files->cd = files->rt;
}
int main(void) {
/*
Filesystem *files;
files = malloc(sizeof(Filesystem));
files->rt = malloc(sizeof(Directory));
char nv[] = "/";
files->rt->name = nv;
files->cd = files->rt;
printf("%s", files->cd->name);
---------------------------------------------------------------------------
Why does the FOLLOWING code not work when the ABOVE code should be "the same" ?
---------------------------------------------------------------------------
*/
Filesystem *f;
mkfs(f);
printf("%s", f->cd->name);
return (EXIT_SUCCESS);
}
最佳答案
当你这样打电话的时候
mkfs(f);
f
的副本被传递给 mkfs。
该副本是被更改的副本(即 malloc 的返回值用于初始化该副本。但是,main
中的 f
未更改。
因此当你这样做的时候
printf("%s", f->cd->name);
在 main 中 - 这是未定义的行为,因为您正在访问未初始化的指针。
你的程序还有其他问题
您的 nv
是函数的局部变量。它的生命只是直到函数返回。所以这是错误的。
关于c - 两段看似相同的代码却有不同的结果(将指针传递给结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15700130/