我需要将用户的输入存储到字符串数组中。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *history[10] = {0};
int main (void) {
char input[256];
input = "input";
strcpy(history[0], input);
return (EXIT_SUCCESS);
}
在终端上运行它,我得到一个分段错误,在 NetBeans 中,我得到 main.c:11: error: incompatible types in assignment。我还尝试移动所有历史记录以将最新输入存储到第一个位置(历史记录[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:空
ETC。
如果输入是“新”
历史 0:新
历史1:新
历史 2:空
ETC。
每次输入新的输入时,指向字符串的指针都会移动,但这只会导致最新的值保存在历史数组中。
您需要为字符串分配空间。这可以通过多种方式完成,两个主要的竞争者如下所示:
char history[10][100];
and
char *history[10];
for (j = 0; j < 10; ++j)
history [j] = malloc (100);
第一个静态分配 10 个字符缓冲区,每个缓冲区 100 个字符。正如您所写,第二个静态分配十个指向字符的指针。通过用动态分配的内存(每个可以是任意长度)填充指针,以后就有内存可以读取字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)