0

私は C 言語を学んでおり、動的メモリ割り当てについて質問があります。
プログラムを終了するには、ユーザーが数字を入力するか、文字「E」を入力する必要があるプログラムがあるとします。ユーザーが入力する数値は、1 次元配列に格納する必要があります。この配列は、1 つの位置から始まります。
ユーザーがこの数値をこの新しい位置に格納するために入力する各数値に整数の配列を増やすにはどうすればよいですか? ポインターを正しく使用する必要があると思いますか? では、配列に格納された値を出力するにはどうすればよいでしょうか。
私が見つけたすべての例は、初心者にとって理解するのが複雑です。malloc 関数と realloc 関数について読みましたが、どちらを使用すればよいか正確にはわかりません。
誰でも私を助けることができますか?ありがとう!

void main() {
    int numbers[];

    do {
        allocate memory;
        add the number to new position;
    } while(user enter a number)

    for (first element to last element)
        print value;
}
4

1 に答える 1

4

実行時に配列を拡張する必要がある場合は、(ヒープ上で) メモリを動的に割り当てる必要があります。これを行うには、mallocまたは状況に適したreallocを使用できます。

このページの良い例は、あなたが望むものを説明していると思います.: http://www.cplusplus.com/reference/cstdlib/realloc/

上記のリンクからコピーして貼り付けます:

/* realloc example: rememb-o-matic */
#include <stdio.h>      /* printf, scanf, puts */
#include <stdlib.h>     /* realloc, free, exit, NULL */

int main ()
{
  int input,n;
  int count = 0;
  int* numbers = NULL;
  int* more_numbers = NULL;

  do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;

     more_numbers = (int*) realloc (numbers, count * sizeof(int));

     if (more_numbers!=NULL) {
       numbers=more_numbers;
       numbers[count-1]=input;
     }
     else {
       free (numbers);
       puts ("Error (re)allocating memory");
       exit (1);
     }
  } while (input!=0);

  printf ("Numbers entered: ");
  for (n=0;n<count;n++) printf ("%d ",numbers[n]);
  free (numbers);

  return 0;
}

配列のサイズはcount変数を使用して記憶されることに注意してください

于 2014-03-12T16:18:33.797 に答える