重新分配指针数组

rai*_*ker 1 c realloc

这是我的程序的一部分。parameters.path是一个字符串,其中包含我将使用的文件的路径,但这不在此代码中。

typedef struct directory {

   char *name;
   char *path;

} directory;

void insertDir(directory*** array , char * path, char* name, int* length) {

    directory *p = malloc(sizeof(directory));

    p->path = malloc(strlen(path)+ 1);
    strcpy(p->path, path);

    p->name = malloc(strlen(name)+ 1);
    strcpy(p->name, name);

    *array = (directory**) realloc( *array , (*length) * (sizeof(directory*)));
    *array[(*length)] = p;
    (*length)++;

}

int main(int argc , char** argv) {

    directory** array = NULL;

    int lenght = 0;

    while(true) {
        insertDir(&array, parameters.path, name , &lenght);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它在第三次失败时出现realloc分段错误。你能帮我吗?

Bar*_*mar 6

执行 时realloc(),您需要将长度加 1,因为您还没有增加它。

*array = realloc( *array , (*length + 1) * (sizeof(directory*)));
Run Code Online (Sandbox Code Playgroud)

您还需要更改:

*array[(*length)] = p;
Run Code Online (Sandbox Code Playgroud)

到:

(*array)[*length] = p;
Run Code Online (Sandbox Code Playgroud)

因为下标运算符的优先级高于解引用运算符。请参阅此处的 C 运算符优先级表。里面也不需要括号[]