私は知っているように、私は次のように内部の項目を持つ配列を作成することができます。
char *test1[3]= {"arrtest","ao", "123"};
しかし、上記のコードのように入力を配列に格納するにはどうすればよいのでしょうか。
input[10];
scanf("%s",&input) or gets(input);
で、各文字が各スペースに格納されます。
入力の "HELLO" が input[0] に格納されるようにするには、どうすればよいのでしょうか。
Hをinput[0]に、Eをinput[1]に、といった具合です。
2次元配列 char input[3][10];
を使用する。
または
charポインタの配列 (
char *input[3];` など) は、その場所に値が保存される前に、動的にメモリが割り当てられる必要があります。
最初のケースは、入力値を scanf("%s", input[0]);
とし、同様に input[1]
と input[2]
も入力値とします。各 input[i]
には最大サイズ 10
('\0'
文字を含む) の文字列を格納できることを覚えておいてください。
第二のケースは、上記と同じ方法で入力を取得しますが、各ポインタ input[i]
に malloc
を使ってメモリを確保する前にします。この場合、各文字列のサイズを柔軟に変更することができます。
何が必要なのかよくわからなかった。しかし、以下は私が推測したものです。
char *a[5];//array of five pointers
for(i=0;i<5;i++)// iterate the number of pointer times in the array
{
char input[10];// a local array variable
a[i]=malloc(10*sizeof(char)); //allocate memory for each pointer in the array here
scanf("%s",input);//take the input from stdin
strcpy(a[i],input);//store the value in one of the pointer in the pointer array
}
以下のコードを試してみてください。
char *input[10];
input[0]=(char*)malloc(25);//mention the size you need..
scanf("%s",input[0]);
printf("%s",input[0]);