的strcpy()和字符串数组 [英] strcpy() and arrays of strings

查看:209
本文介绍了的strcpy()和字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要来自用户的输入存储到字符串数组

I need to store the input from a user into an array of strings.

#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])。

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.

如果输入的是输入

历史0:输入
历史1:空
等等。

History 0: input History 1: null etc.

如果再输入新

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

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];

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

第一个静态分配在每100个字符十个字符的缓冲区。第二,当你写的,静态分配10指针字符。通过在终场前动态分配的内存填充(这可能是每一个任意长度),有记忆稍后阅读的字符串。

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.

这篇关于的strcpy()和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆