C char指针动态分配——分配一个未知长度的值

标签 c pointers char

我对这里发生的事情感到很困惑。

while ( (ent = readdir(dir)) != NULL)
    {
        char *name = ent -> d_name;
        ....
    }

这只是扫描目录的一些基本代码。很公平。但我无法理解这是如何编译的,因为编译器如何以...的名义确定 ent -> d_name 的大小?在编译时没有人知道它,必须为此分配内存,对吗?编译器是自动为我 malloc() 还是什么? 如果相关的话,我在 Ubuntu 下使用 GCC。

提前致谢。

最佳答案

  • 编译器能否确定 ent -> d_name 的大小?

编译器不需要。

在 Linux 上,dirent 结构定义如下:

struct dirent {
    ino_t          d_ino;       /* inode number */
    off_t          d_off;       /* offset to the next dirent */
    unsigned short d_reclen;    /* length of this record */
    unsigned char  d_type;      /* type of file; not supported
                                   by all file system types */
    char           d_name[256]; /* filename */
};

在此之后

char *name = ent -> d_name;

name 只是指向数组 ent->d_name 的第一个元素。

  • 编译器是自动为我 malloc() 还是什么?

这里

while ( (ent = readdir(dir)) != NULL)

readdir 返回指向 dirent 结构的指针。

男人是这样说的:

On success, readdir() returns a pointer to a dirent structure. (This structure may be statically allocated; do not attempt to free(3) it.)

显然 readdir 为您分配了内存。

另请阅读:why does the C readdir man page say to not call free on the static allocated result struct

关于C char指针动态分配——分配一个未知长度的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17387467/

相关文章:

c - 代码有什么问题吗?打印值不符合预期

c - UTF-16 字符串终止符

c - 使用指针 : program that checks if strings are in lexicographical order

c++ - unique_ptr 的 remove_pointer

使用 char 数组的 C 结构初始化

C 导航,无法编译

c - 为什么我的 C 代码运行缓慢?

c - 测试迭代指针之间的关系是否安全?

java - StringIndexOutOfBoundsException while 循环与charat()

c++ - UTF-8 char * 到 CString 的转换