strcpy()和字符串数组
我需要将用户的输入存储到字符串数组中。
#include #include #include char *history[10] = {0}; int main (void) { char input[256]; input = "input"; strcpy(history[0], input); return (EXIT_SUCCESS); }
在终端上运行它我得到一个分段错误,在NetBeans中我得到main.c:11:错误:赋值中不兼容的类型。 我还尝试将所有历史记录移动到最新输入到第一个位置(历史[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;
但这导致这样的输出。
如果输入是“输入”
历史0:输入历史1:null等
如果那么输入是“新的”
历史0:新历史1:新历史2:null等
每次输入新输入时,指向字符串移位的指针,但它只会将最新值保存在历史数组中。
您需要为字符串分配空间。 这可以通过多种方式完成,两个主要竞争者看起来像:
char history[10][100];
和
char *history[10]; for (j = 0; j < 10; ++j) history [j] = malloc (100);
第一个静态分配10个字符缓冲区,每个缓冲区100个字符。 第二个,就像你写的那样,静态地分配十个指向字符的指针。 通过用动态分配的内存(每个都可以是任意长度)填充指针,稍后会有内存来读取字符串。
strcpy()
不为字符串分配新的内存区域,它只将数据从一个缓冲区复制到另一个缓冲区。 您需要使用strdup()
分配新缓冲区或创建预分配的数组( char history[10][100];
)。 在这种情况下,不要尝试移动指针并使用strcpy
复制数据。
main.c:11: error: incompatible types in assignment (Code: input = "input";)
发生这种情况是因为您尝试使数组’input’指向字符串“input”。 这是不可能的,因为数组是一个const指针(即它指向的值不能改变)。
做你正在尝试的正确方法是:
strcpy(input,"input");
当然这是一个小问题,主要问题已经发布了两次。 只是想指出来。
顺便说一下,我不知道你在终端上运行它时如何编译它。 你不知道错误吗? 也许只是一个警告? 尝试使用-Wall -pedantic进行编译