c - C 中的字符串数组

标签 c arrays string

我写了一个读取文件的代码

下面的代码有什么问题,如果我打印任何 arrayItem,我总是得到最后一个文件名

#include <stdio.h>
#include <string.h>

char **get_files()
{
    FILE *fp;
    int status;
    char file[1000];
    char **files = NULL;
    int i = 0;
    /* Open the command for reading. */
    fp = popen("ls", "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        //exit;
    }

    while (fgets(file, sizeof(file)-1, fp) != NULL) {

        files = (char **)realloc(files, (i + 1) * sizeof(char *));
        //files[i] = (char *)malloc(sizeof(char));
        files[i] = file;
        i++;        
    }
    printf("%s", files[0]);
    return files;
}

int main()
{
char **files = NULL;
int i =0 ;
files = get_files("");

}

最佳答案

你应该使用

files[i] = strdup(file);

而不是

files[i] = file;

第二个版本仅让files[i]指向始终相同的读取缓冲区。使用下一个 fgets,您将覆盖 file 的内容,从而覆盖实际上指向同一位置的 file[i] 的内容在内存中。 事实上,最后,所有 file[0]..file[n] 将指向与 file 相同的位置。

使用strdup(..),您可以分配一个新的缓冲区并将file的内容复制到那里。

关于c - C 中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3653907/

相关文章:

c# - 从datagridview获取数据到字符串

c - 结构矩阵的 malloc - C

c - 了解malloc

sql - 将项目数组存储在SQL表中

PHP array_multisort 没有正确排序第二个数组

regex - 如何在子目录中的所有java文件中grep一个字符串?

c - 简单的程序检查 ip - scanf 段错误

c++ - 如果你使用 char *ptr 存储整型变量的地址会发生什么

c# - XML 反序列化和松散数组项

java - String.length() 和 String.getBytes().length 之间的区别