2010-10-10 106 views
3

我需要将来自用户的输入存储到字符串数组中。strcpy()和字符串数组

#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:错误:不兼容的类型分配。我也尝试移动所有历史记录以将最新输入存储到第一个位置(历史[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:空 等

如果然后输入是 “新”

历史0:新 历史1:新 历史2:空 等

每次输入新的输入指向字符串转换的指针,但它只会导致最新的VA将被保存在历史数组中。

回答

4

您需要为字符串分配空间。这可以通过多种方式,两个主要的竞争者是这样的:

char history[10][100]; 

char *history[10]; 
for (j = 0; j < 10; ++j) 
    history [j] = malloc (100); 

第一静态分配在每100个字符十个字符的缓冲区。第二,如你所写,静态分配十个指向字符的指针。通过用动态分配的内存(每个内存可以是任意长度)填充指针,稍后有内存可以读取该字符串。

1

strcpy()不为字符串分配新的内存区域,它只将数据从一个缓冲区复制到另一个缓冲区。您需要使用strdup()分配新缓冲区或创建预分配阵列(char history[10][100];)。在这种情况下,请勿尝试移动指针并使用strcpy复制数据。

0
main.c:11: error: incompatible types in assignment 
(Code: input = "input";) 

发生这种情况是因为您尝试使数组输入指向字符串“input”。这是不可能的,因为数组是一个const指针(即它指向的值不能改变)。

正确的方法做你正在尝试的是:

strcpy(input,"input"); 

当然,这是一个小问题,主要的问题已经发布了两次。只是想指出来。

顺便说一句,我不知道你甚至编译时,如何在终端上运行它。你没有得到一个错误?也许只是一个警告?尝试使用-Wall -pedantic编译