将字符串从指针复制到指针数组中的索引

标签 c arrays pointers

如标题所述,我想将字符串从 char 指针复制到 char 指针数组中的位置。执行strcpy()时,输出结果出现seg错误,但不明白为什么会出现这种情况。

缩写代码如下:

void make_history(char *entry) {
    //static char past_entries[10][10];
    static char *past_entries[10];
    static int index = 0;
    static int array_index = 0;

    char *input;
    if((input = strchr(entry, '\n')) != NULL)
        *input = '\0';

    if(strcmp(entry, "history") != 0) {
        strcpy(past_entries[index], entry);
        *past_entries[index] = &entry;
        index = (index + 1) % 10;
        array_index++;
    }
}

我认为将日期从 entry 复制到指针数组 past_entries 内的位置会更容易,而不是尝试返回二维数组(这也非常棘手) 。同样,strcpy 不起作用,是否有发生这种情况的有效原因,以及此修复的可能解决方法或解决方案?

谢谢

最佳答案

在您的示例中,past_entries 只是一个指针数组,但您没有为它们分配任何内存(最初指向NULL)。然后您尝试写入这些位置,因此崩溃。

要解决此问题,只需在尝试将字符串复制到其中之前分配一些内存即可:

past_entries[index] = malloc(strlen(entry) + 1);

当然,你不应该忘记最后释放所有这些。

哦,删除该行:*past_entries[index] = &entry;。它尝试将指向字符数组的指针分配给字符

关于将字符串从指针复制到指针数组中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52517664/

相关文章:

c - 以下 strtok() 用法有什么问题?

javascript - (new Array(x)).map 奇怪

c - 同时运行的自旋锁

c - 将字符串添加到 sprintf 中

c - 与 Node 和 Node-gyp 一起使用的 AWS Lambda 上出现奇怪的 "memory"行为

javascript - 我如何在javascript中访问数组中的数组

c# - C#中填充矩形数组的扩展方法

list - 如何更新 go 列表中的下一个指针?

c - 具有这种形式的链表/指针 list[0]

c - 使用自动更新的指针结构