I need to store the input from a user into an array of strings.
#include
#include
#include
char *history[10] = {0};
int main (void) {
char input[256];
input = "input";
strcpy(history[0], input);
return (EXIT_SUCCESS);
}
Running it on the terminal I get a Segmentation Fault and in NetBeans I get main.c:11: error: incompatible types in assignment. I also tried to shift all the history to store the newest input into the first position (history[0]).
history[9] = history[8];
history[8] = history[7];
history[7] = history[6];
history[6] = history[5];
history[5] = history[4];
history[4] = history[3];
history[3] = history[2];
history[2] = history[1];
history[1] = history[0];
history[0] = input;
But this causes output like this.
If input is "input"
History 0: input
History 1: null
etc.
If then input is "new"
History 0: new
History 1: new
History 2: null
etc.
Each time a new input is entered the pointers to the string shift but it causes only the newest value to be saved in the history array.
解决方案
You need to allocate space for the string. This can be done several ways, the two leading contenders look like:
char history[10][100];
and
char *history[10];
for (j = 0; j < 10; ++j)
history [j] = malloc (100);
The first statically allocates ten character buffers at 100 characters each. The second, as you wrote it, statically allocates ten pointers to characters. By filling in the pointer with dynamically allocated memory (which could each be arbitrary lengths), there is memory to read the string later.
本文探讨了如何在C语言程序中避免Segmentation Fault,通过使用动态内存分配存储用户输入的字符串数组。作者介绍了错误的代码片段,并提供了正确的方法,即使用字符数组动态扩容,以确保历史记录的正确保存和更新。
800

被折叠的 条评论
为什么被折叠?



