如标题所述,我想将字符串从 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/